是的,我知道我完全会看起来像个白痴,但我的大脑只是not今天早上开始工作。
我想要一种方法,我可以说“如果它变坏,则返回这种类型的异常”,对吧?
例如,类似(这不起作用):
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
现在令我困惑的是我们KNOW由于以下原因,泛型类型将成为异常类型where条款。但是,代码失败了,因为我们无法隐式强制转换例外 to ExType。我们也不能显式地转换它,例如:
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
因为这也失败了..所以这种事情可能吗?我有一种强烈的感觉,它会非常简单,但我的老头脑度过了艰难的一天,所以让我放松一下:P
Update
谢谢楼上各位的回复,看来不是我的问题complete笨蛋! ;)
OK, so Vegard https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398 and Sam https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404让我到达了可以实例化正确类型的地步,但随后显然陷入了困境,因为message参数在实例化后是只读的。
Matt https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408他的回答一语中的,我已经对此进行了测试,一切正常。这是示例代码:
static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
甜的! :)
多谢你们!