Create Instantiate Object Handler - CSharp System.Reflection

CSharp examples for System.Reflection:ConstructorInfo

Description

Create Instantiate Object Handler

Demo Code


using System.Reflection.Emit;
using System.Reflection;
using System;//from   w  ww  .  j  a  va 2  s .  c o m

public class Main{
        // DynamicMethodCompiler

        // CreateInstantiateObjectDelegate
        public static InstantiateObjectHandler CreateInstantiateObjectHandler(Type type)
        {
            ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
            if (constructorInfo == null)
            {
                throw new ApplicationException(string.Format("The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).", type));
            }

            var dynamicMethod = new DynamicMethod("InstantiateObject", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), null, type, true);
            ILGenerator generator = dynamicMethod.GetILGenerator();
            generator.Emit(OpCodes.Newobj, constructorInfo);
            generator.Emit(OpCodes.Ret);
            return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
        }
}

Related Tutorials