I want to use Reflection Emit to instantiate a class with arbitrary constructor parameters. This is what my code looks like:
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);
Code failure with MethodAccessException with error message 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. .
What is going wrong?
source share