gpt4 book ai didi

c# - Reflection Emit 创建类实例

转载 作者:太空狗 更新时间:2023-10-30 01:07:07 25 4
gpt4 key购买 nike

我想使用 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错误消息 Attempt by method 'DynamicClass.CreateInstance(System.Object[])' to access method '<>f__AnonymousType1'3<System.Int32,System.__Canon,System.__Canon>..ctor(Int32, System.__Canon, System.__Canon)' failed. .

出了什么问题?

最佳答案

错误消息表明匿名类型的构造函数不是公开的。我认为匿名类型构造函数始终是内部,因此您需要使用不同的DynamicMethod 构造函数来跳过可见性检查:

DynamicMethod method = new DynamicMethod("CreateInstance", typeof(object), new Type[] { typeof(object[]) }, true);

请注意,这不适用于部分信任的情况。

关于c# - Reflection Emit 创建类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13478933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com