I'm working on an app that creates a number of objects with a standard constructor by using assembly.CreateInstance()
which all works as expected.
The complication however comes when the constructor raises an exception which is then raised in the calling code as a TargetInvocationException
with the InnerException
property set.
Is there a way to get Visual Studio to debug the exception as it does if I was calling the constructor directly?
I'm thinking of temporarily making it a switch block based on the type name, but this won't help when the objects are in a different (non referenced) assembly.
Sample code:
namespace CreateInstanceTest {
public static class Program {
[STAThread]
public static void Main() {
Type testType = typeof(TestClass);
Tes开发者_JAVA百科tClass test = (TestClass)testType.Assembly.CreateInstance(testType.FullName, false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { "value" }, null, null);
}
}
public class TestClass {
public TestClass(string param) {
throw new Exception("My exception");
}
}
}
Thanks.
For debugging, I ended up using something similar to:
BuildAction action = null; //(BuildAction)actionType.Assembly.CreateInstance(actionType.FullName, true, System.Reflection.BindingFlags.CreateInstance, null, new object[] { subReader, format }, null, null);
switch (actionType.Name) {
case "SetVariable":
action = new Actions.SetVariable((XmlReader)subReader, format);
break;
case "DisplayMessage":
action = new Actions.DisplayMessage((XmlReader)subReader, format);
break;
}
Which bypasses the dynamic CreateInstance
call.
精彩评论