若我传递参数,c#Activator.CreateInstance无法从实例化的类捕获异常
我使用Activator.CreateInstance实例化动态类,如果出现问题,我的类构造函数将生成异常 当我使用无参数构造函数(测试1)时,我可以捕获CreateInstance周围实例化类启动的异常 但是,如果我使用带参数的构造函数,则CreateInstance周围的try catch不会捕获异常 我怎样才能抓住这个例外若我传递参数,c#Activator.CreateInstance无法从实例化的类捕获异常,c#,exception-handling,C#,Exception Handling,我使用Activator.CreateInstance实例化动态类,如果出现问题,我的类构造函数将生成异常 当我使用无参数构造函数(测试1)时,我可以捕获CreateInstance周围实例化类启动的异常 但是,如果我使用带参数的构造函数,则CreateInstance周围的try catch不会捕获异常 我怎样才能抓住这个例外 using System; using System.Text; namespace ConsoleApplication1 { public abstra
using System;
using System.Text;
namespace ConsoleApplication1
{
public abstract class Base
{
public Base()
{
throw new Exception(" -= TEST = Bad filename. =- ");
}
public Base( String filename)
{
throw new Exception(" -= TEST = Bad filename. =- ");
}
}
public class Child : Base
{
public Child()
: base()
{
}
public Child(String filename)
: base(filename)
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
Base child = (Base)Activator.CreateInstance(typeof(Child));
}
catch (Exception e)
{
Console.WriteLine("Test 1 (no argument): Catch OK");
Console.WriteLine(e.ToString());
}
Console.WriteLine("Test 1: OK\n--------------------------");
Console.ReadKey();
try
{
Base child = (Base)Activator.CreateInstance(typeof(Child), "foo");
}
catch (Exception e)
{
Console.WriteLine("Test 2 (with argument): Catch OK");
Console.WriteLine(e.ToString());
}
Console.WriteLine("The end");
Console.ReadKey();
}
}
}
不,不能复制这个。也许你是单声道的吧?您使用的是什么版本的.NET?操作系统呢?很可能您的实际代码显示的错误与示例代码不同(这很好);您必须找到可复制的错误,否则我们无法帮助您。也无法复制它(.NET 4.5.2)。我使用.NET 4.5、Visual Studio 2012和Windows 8.1。示例生成了一个未处理的异常。您是否确实运行了发布的代码,以确保它重现了导致您首先遇到问题的问题?此代码中没有任何内容会导致您报告的行为,而且您发布的代码确实不会重现问题。这是一个很好的代码示例,但它没有达到必须重现问题的关键标准。在我的环境中,测试1是正常的,当我按下一个键运行测试2时,VisualStudio显示对话框:关于此部分的未处理异常:
public Base(String filename){throw new exception(“-=Test=Bad filename.=-”);}
我从出现问题的真实程序中制作了此示例。我正在更新到.NETFramework4.5.2,可能是一个4.5错误。