using System; using System.Reflection; using System.Reflection.Emit; [MenuItem("Toole/Test", false)] public static void Test() { var call = CreateCtor(typeof(AA)); var tag = call.Invoke(); if(tag != null) { } } public class AA { public int a = 100; } public static ObjectActivator CreateCtor(Type type) { if(type == null) { throw new NullReferenceException("type"); } ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes); var dynamicMethod = new DynamicMethod("CreateInstance", type, Type.EmptyTypes, true); ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Nop); ilGenerator.Emit(OpCodes.Newobj, emptyConstructor); ilGenerator.Emit(OpCodes.Ret); return (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator)); } public delegate object ObjectActivator();
|
|
来自: tiancaiwrk > 《C#》