lundi 9 avril 2018

Reflectively call constructor which throws an exception

I'm trying to create an instance of System.RuntimeType which has a very annoying constructor:

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

Normally you could just try/catch it and the object will have been constructed, even though the exception was thrown. However, being internal, I have to use reflection to call these, and the exception will get wrapped into a TargetInvocationException and the object thrown away:

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() is marked extern so I can't see how exactly it works to reverse-engineer it without the wrapping. Is there any way to get this type constructed?





Aucun commentaire:

Enregistrer un commentaire