c# – Reflection Emit创建类实例
作者:互联网
我想使用Reflection Emit来创建具有任意构造函数参数的类的实例.这是我的代码的样子:
public delegate object ObjectActivator(params object[] args);
static void Main(string[] args)
{
var ao = new { ID = 10000, FName = "Sample", SName = "Name" };
var t = ao.GetType();
var info = t.GetConstructor(new Type[] { typeof(int), typeof(string), typeof(string) });
var objActivatorEmit = GetActivatorEmit(info);
var obj = createdActivatorEmit(4, "Foo", "Bar");
}
public static ObjectActivator GetActivatorEmit(ConstructorInfo ctor)
{
ParameterInfo[] paramsInfo = ctor.GetParameters();
DynamicMethod method = new DynamicMethod("CreateInstance", typeof(object), new Type[] { typeof(object[]) });
ILGenerator gen = method.GetILGenerator();
for (int i = 0; i < paramsInfo.Length; i++)
{
Type t = paramsInfo[i].ParameterType;
gen.Emit(OpCodes.Ldarg_0); // Push array (method argument)
gen.Emit(OpCodes.Ldc_I4, i); // Push i
gen.Emit(OpCodes.Ldelem_Ref); // Pop array and i and push array[i]
if( t.IsValueType )
{
gen.Emit( OpCodes.Unbox_Any, t ); // Cast to Type t
}
else
{
gen.Emit( OpCodes.Castclass, t ); //Cast to Type t
}
}
gen.Emit(OpCodes.Newobj, ctor);
gen.Emit(OpCodes.Ret);
return (ObjectActivator)method.CreateDelegate(typeof(ObjectActivator));
}
代码失败,出现MethodAccessException,错误消息由方法’DynamicClass.CreateInstance(System.Object [])’尝试访问方法’<> f__AnonymousType1’3< System.Int32,System .__ Canon,System .__ Canon>. .ctor(Int32,System .__ Canon,System .__ Canon)’失败..
出了什么问题?
解决方法:
该错误消息表明匿名类型的构造函数不是公共的.我认为匿名类型构造函数总是内部的,因此您需要使用不同的DynamicMethod构造函数跳过可见性检查:
DynamicMethod method = new DynamicMethod("CreateInstance", typeof(object), new Type[] { typeof(object[]) }, true);
请注意,这在部分信任方案中不起作用.
标签:c,reflection,reflection-emit,il 来源: https://codeday.me/bug/20190620/1246825.html