扩展方法需要动态泛型类型的异常 [英] Extension method to Exception requiring dynamic generic type
问题描述
此问题以前以不同的方式提出,但答案并不能帮助我,因为(1)我无法控制内置的异常
类,和(2) Activator.CreateInstance()
返回一个对象/实例,我需要一个真正的动态类型。
This question has been asked in different ways before, but the answers don't help me, because (1) I don't have control over the built-in Exception
classes, and (2) Activator.CreateInstance()
returns an object/instance, where I need a true dynamic type.
我正在尝试创建一个扩展方法,允许我从我的WCF服务中抛出一个 FaultException
,这是基于我捕获的异常。例如:
I'm trying to create an extension method that allows me to throw a FaultException
out of my WCF service, based off the exception I catch. For example:
try {
...
}
catch (ArgumentNullException exc) {
throw new FaultException<ArgumentNullException>(exc);
}
是直截了当的。但是,如果我想以一般的方式来扩展它,我会使用扩展类,例如:
is straight-forward. But if I want to extend this in a general way, I'd use an extension class, like:
try {
...
}
catch (Exception exc) {
exc.ThrowFaultException();
}
我挂断了,当然是扩展方法的实现:
Where I get hung up, of course, is the implementation of the extension method:
public static void ThrowFaultException(this Exception exc) {
// Gives me the correct type...
Type exceptionType = exc.GetType();
// But how the heck do I use it?
throw new FaultException<???>(exc);
}
The answers here and here don't help. Any ideas?
推荐答案
尝试这样:
public static void ThrowFaultException<TException>(this TException ex) where TException : System.Exception
{
throw new FaultException<TException>(ex);
}
这篇关于扩展方法需要动态泛型类型的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!