我从未想过这种情况,因此我很好奇并进行了一些简单的实现。首先,以下内容有效:
public class WebFaultException : Exception
{
public WebFaultException() { }
public WebFaultException(string message) : base(message) { }
public WebFaultException(string message, Exception innerException) : base(message, innerException) { }
protected WebFaultException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
public class WebFaultException<T> : WebFaultException
{
public WebFaultException() { }
public WebFaultException(string message) : base(message) { }
public WebFaultException(string message, Exception innerException) : base(message, innerException) { }
protected WebFaultException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) {}
}
当您的异常定义和这些测试都通过时:
[TestMethod]
public void SpecificGeneric()
{
bool hitException = false;
try
{
throw new WebFaultException<string>();
}
catch(WebFaultException<string> e)
{
hitException = true;
}
Assert.IsTrue(hitException);
}
[TestMethod]
public void AnyGeneric()
{
bool hitException = false;
try
{
throw new WebFaultException<int>();
}
catch (WebFaultException<string> e)
{
hitException = false;
}
catch (WebFaultException e)
{
hitException = true;
}
Assert.IsTrue(hitException);
}
就你想要的特定做法而言,有一个问题。在你提供的代码中,WebDefaultException<T>
是没有意义的,因为你没有提供T。不过,你可以通过如下方式(有些笨拙)避免这个问题(另一个单元测试通过):
[TestMethod]
public void CallingGenericMethod()
{
Assert.IsTrue(GenericExceptionMethod<int>());
}
private bool GenericExceptionMethod<T>()
{
bool hitException = false;
try
{
throw new WebFaultException<int>();
}
catch (WebFaultException<string> e)
{
hitException = false;
}
catch (WebFaultException<T> e)
{
hitException = true;
}
return hitException;
}
也就是说,如果你处理异常的方法(或类)具有泛型参数,则实际上可以捕获
WebFaultException<T>
。但是我要提醒一句话,这样做非常奇怪 - 作为您方法的客户端,我被迫传入一个对我来说无关紧要且是您内部实现细节的类型,用于捕获某个异常。
所以,我会说是可以的。但最好还是尽量避免使用,因为这样做可能会让人感到尴尬或者不明智。
WebFaultException<T>
有基类吗? - leppieWebFaultException<T>
... - bitbonk