[英]Extension method to Exception requiring dynamic generic type
之前已經以不同的方式提出了這個問題,但是答案無濟於事,因為(1)我無法控制內置的Exception
類,並且(2) Activator.CreateInstance()
返回一個對象/例如,我需要一個真正的動態類型。
我正在嘗試創建一個擴展方法,該方法允許我根據捕獲到的異常將FaultException
從WCF服務中拋出。 例如:
try {
...
}
catch (ArgumentNullException exc) {
throw new FaultException<ArgumentNullException>(exc);
}
是直截了當的。 但是,如果我想以一般方式擴展它,則可以使用擴展類,例如:
try {
...
}
catch (Exception exc) {
exc.ThrowFaultException();
}
我掛斷電話的地方當然是擴展方法的實現:
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);
}
嘗試這個:
public static void ThrowFaultException<TException>(this TException ex) where TException : System.Exception
{
throw new FaultException<TException>(ex);
}
您無需將Activator.CreateInstance返回的對象強制轉換為FaultException <? 將其強制轉換為Exception即可:
var type = typeof(FaultException<>).MakeGenericType(exc.GetType());
throw (Exception)Activator.CreateInstance(type, exc);
我不會在ThrowFaultException
拋出異常:
try
{
...
}
catch (Exception e)
{
throw e.WrapInFaultException();
}
public static Exception WrapInFaultException(this Exception e)
{
var type = typeof(FaultException<>).MakeGenericType(e.GetType());
return (Exception)Activator.CreateInstance(type, e);
}
public static void ThrowFaultException(this Exception exc)
{
// Gives me the correct type...
Type exceptionType = exc.GetType();
var genericType = typeof(FaultException<>).MakeGenericType(exceptionType);
// But how the heck do I use it?
throw (Exception)Activator.CreateInstance(genericType, exc);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.