繁体   English   中英

使用Assembly.CreateInstance()时调试构造函数异常

[英]Debugging constructor exceptions when using assembly.CreateInstance()

我正在开发一个应用程序,该应用程序通过使用assembly.CreateInstance()使用标准构造函数创建许多对象,这些对象均按预期工作。

但是,当构造函数引发异常时,问题就复杂了,该异常随后在调用代码中作为具有InnerException属性集的TargetInvocationException 如果我直接调用构造函数,有没有办法使Visual Studio调试异常?

我正在考虑根据类型名称暂时将其设置为一个开关块,但这在对象位于不同(未引用)程序集中时无济于事。

样例代码:

namespace CreateInstanceTest {
    public static class Program {
        [STAThread]
        public static void Main() {
            Type testType = typeof(TestClass);
            TestClass 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");
        }
    }
}

谢谢。

对于调试,我最终使用类似于以下内容的东西:

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;
}

绕过动态CreateInstance调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM