反复调用抛出异常的构造函数

时间:2018-04-09 13:16:38

标签: c# reflection

我正在尝试创建一个System.RuntimeType的实例,它有一个非常讨厌的构造函数:

internal class RuntimeType
{
    internal RuntimeType()
    {
        throw new NotSupportedException();
    }
}

通常你可以尝试/捕获它,即使引发了异常,也会构造对象。但是,作为internal,我必须使用反射来调用这些,并且异常将被包装到TargetInvocationException中并且该对象被丢弃:

System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----> System.NotSupportedException : Specified method is not supported.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
   at Application.Util.Constructor.RuntimeType() in C:\Work\Application\src\Application\Util\Constructor.cs:line 300
   at Tests._4._5.Util.ConstructorTests.RuntimeType() in C:\Work\Application\src\Tests\Tests.4.5\Util\ConstructorTests.cs:line 159
--NotSupportedException
   at System.RuntimeType..ctor()

System.RuntimeMethodHandle.InvokeMethod()被标记为extern,所以我无法看到它如何在没有包装的情况下对其进行反向工程。有没有办法构建这种类型?

1 个答案:

答案 0 :(得分:2)

FormatterServices.GetUninitializedObject方法可以在不调用构造函数的情况下创建对象:

  

返回类型:System.Object

     

指定类型的归零对象。

https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject(v=vs.110).aspx