public static DefaultCreatorDelegate CreateDefaultConstructorDelegate(Type type)
{
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[0],
null);
if (constructorInfo == null)
{
throw new Exception(
string.Format(
"The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).",
type));
}
#if !CompactFramework
DynamicMethod 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 (DefaultCreatorDelegate)dynamicMethod.CreateDelegate(typeof(DefaultCreatorDelegate));
#else
return () => constructorInfo.Invoke(null);
#endif
}