2 回答

TA貢獻1809條經驗 獲得超8個贊
正如 Yacoub Massad 建議您可以使用dynamic,因為dynamic方法重載解析在運行時通過后期綁定推遲:
public static class Extensions
{
public static string GetString<T>(this T e) where T : Exception
{
// dynamic method overload resolution is deferred at runtime through late binding.
return GetStringCore((dynamic)e);
}
static string GetStringCore(Exception e)
{
return "Standard!!!";
}
static string GetStringCore(TimeoutException e)
{
return "TimeOut!!!";
}
static string GetStringCore(InvalidOperationException e)
{
return "Invalid!!!";
}
}
這應該可以解決問題。

TA貢獻1852條經驗 獲得超7個贊
擴展方法在這里是錯誤的工具。
我會提倡使用多態來解決您的問題:
public abstract class BaseException : Exception
{
public abstract string GetString();
}
public sealed class TimeoutException : BaseException
{
public override string GetString() => "TimeOut!!!";
}
public sealed class MyException : BaseException
{
public override string GetString() => "Standard!!!";
}
用法
try
{
throw new TimeoutException(); //or whatever BaseException's children
}
catch (BaseException e)
{
//here I'm assuming you know that you are swallowing the exception (which may be an anti-pattern)
Console.WriteLine(e.GetString());
}
編輯
看起來您無法完全控制引發異常的時間和地點。另一種可能性是為每個行為(而不是每個異常類型)添加 1 個 catch 子句并刪除GetString():
try
{
throw new TimeoutException();
}
catch (Exception e) when (e is ArgumentNullException || e is FormatException)
{
//do something
}
catch (Exception e) when (e is TimeoutException)
{
//do something
}
catch (Exception e)
{
throw new NotImplementedException($"Hey Mike, write something for {e.GetType()}, will ya?"); //idea from Jeroen
}
- 2 回答
- 0 關注
- 234 瀏覽
添加回答
舉報