임의의 생성자 매개 변수를 사용하여 클래스의 인스턴스를 생성하려면 Reflection Emit을 사용하고 싶습니다. 이것은 내 코드와 같은 모습입니다 :Reflection 클래스 인스턴스를 생성하기 위해 방출합니다.
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));
}
코드는 오류 메시지 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.
과 MethodAccessException
실패합니다.
무엇이 잘못 되었나요?
나는 그것이 일반 대중 ctor라고 생각합니다. http://blogs.msdn.com/b/ericlippert/archive/2010/12/20/why-are-anonymous-types-generic.aspx – Elisha
@Elisha - 내부 형식의 공용 생성자이므로 여전히 액세스 할 수 없습니다. – kvb
은 현재 정상적으로 작동합니다. – user1622959