My goal is to create a runtime delegate that can set any field (including readonly) in any reference type to a user-defined value. Unfortunately, my current implementation throws VerificationExceptionat runtime when assemblies containing types indicate an attribute [AllowPartiallyTrustedCallers].
AssemblyOne:
[assembly: AllowPartiallyTrustedCallers]
public class TypeOne
{
public TypeOne(TypeTwo typeTwoField)
{
this.TypeTwoField = typeTwoField;
}
public TypeTwo TypeTwoField { get; }
}
AssemblyTwo:
[assembly: AllowPartiallyTrustedCallers]
public class TypeTwo
{
public TypeTwo(int i)
{
this.Int = i;
}
public int Int { get; }
}
Main:
using System;
using System.Reflection;
using System.Reflection.Emit;
using AssemblyOne;
using AssemblyTwo;
namespace Main
{
class Program
{
public class MyType
{
public MyType(TypeOne typeOneField)
{
this.TypeOneField = typeOneField;
}
public TypeOne TypeOneField { get; }
}
static void Main(string[] args)
{
var fieldInfo = typeof(TypeOne)
.GetTypeInfo()
.GetField(
"<TypeTwoField>k__BackingField",
BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
var setter = (Action<TypeOne, TypeTwo>) GetReferenceSetter(fieldInfo);
var myType = new MyType(new TypeOne(new TypeTwo(1)));
setter(myType.TypeOneField, new TypeTwo(2));
}
public static Delegate GetReferenceSetter(FieldInfo field)
{
var delegateType = typeof(Action<,>)
.MakeGenericType(field.DeclaringType, field.FieldType);
var method = new DynamicMethod(
field.Name + "Set",
null,
new[] {field.DeclaringType, field.FieldType},
field.DeclaringType,
skipVisibility: true);
var emitter = method.GetILGenerator();
emitter.Emit(OpCodes.Ldarg_0);
emitter.Emit(OpCodes.Ldarg_1);
emitter.Emit(OpCodes.Stfld, field);
emitter.Emit(OpCodes.Ret);
return method.CreateDelegate(delegateType);
}
}
}
So it MyTypehas TypeOne, which has readonly TypeTwo. In this case, DynamicMethodreturns a VerificationExceptionat run time.
Is it possible to create a delegate that works for any type of declaration of type + that you throw on it? If so, how?
I understand that fields readonlyshould never be set after construction, but the purpose of this is deserialization and deep copying.