题
是的,我知道我完全会看起来像个白痴,但我的大脑只是 不是 今天早上开始工作。
我想要一种方法,我可以说“如果它变坏,则返回这种类型的异常”,对吧?
例如,类似(这不起作用):
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
现在令我困惑的是我们 知道 由于以下原因,泛型类型将成为异常类型 在哪里 条款。但是,代码失败了,因为我们无法隐式强制转换 例外 到 Ex类型. 。我们也不能显式地转换它,例如:
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
因为这也失败了..所以 这种事情可能吗? 我有一种强烈的感觉,它会非常简单,但我的老头脑度过了艰难的一天,所以让我放松一下:P
更新
谢谢各位的回复,看来不是我的问题 完全的 笨蛋!;)
好的,那么 维加德 和 山姆 让我到达了可以实例化正确类型的地步,但随后显然陷入了困境,因为 信息 参数在实例化后是只读的。
马特 他的回答一语中的,我已经对此进行了测试,一切正常。这是示例代码:
static ExType TestException<ExType>(string message) where ExType:Exception, new ()
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
甜的!:)
多谢你们!
解决方案
你几乎可以这样做:
static void TestException<E>(string message) where E : Exception, new()
{
var e = new E();
e.Message = message;
throw e;
}
但是,这不会编译,因为 Exception.Message 是只读的。它只能通过将其传递给构造函数来分配,并且无法使用默认构造函数以外的其他内容来约束泛型类型。
我认为您必须使用反射(Activator.CreateInstance)来“新建”带有消息参数的自定义异常类型,如下所示:
static void TestException<E>(string message) where E : Exception
{
throw Activator.CreateInstance(typeof(E), message) as E;
}
编辑 哎呀刚刚意识到你想要 返回 异常,不抛出它。同样的原则也适用,所以我将用 throw 语句保留我的答案。
其他提示
该解决方案的唯一问题是,可以创建 Exception 的子类,该子类不实现具有单个字符串参数的构造函数,因此可能会引发 MethodMissingException。
static void TestException<E>(string message) where E : Exception, new()
{
try
{
return Activator.CreateInstance(typeof(E), message) as E;
}
catch(MissingMethodException ex)
{
return new E();
}
}
我一直在实例化内联我想要抛出的异常类型,如下所示:
if (ItemNameIsValid(ItemName, out errorMessage))
throw new KeyNotFoundException("Invalid name '" + ItemName + "': " + errorMessage);
if (null == MyArgument)
throw new ArgumentNullException("MyArgument is null");
你有没有尝试过:
static T TestException<Exception>(string message)
{}
因为我有一种感觉,像所有可抛出异常一样,没有必要加入通用约束 必须 无论如何,都是从 System.Exception 继承的。
请记住,泛型确实接受继承的类型。
我认为所有异常都应该有一个无参数构造函数,并且具有 Message
属性,所以以下应该有效:
static ExType TestException<ExType>(string message) where ExType:Exception
{
ExType ex = new ExType();
ex.Message = message;
return ex;
}
编辑:好的,Message 是只读的,因此您必须希望该类实现 Exception(string) 构造函数。
static ExType TestException<ExType>(string message) where ExType:Exception
{
return new ExType(message);
}