Mik*_*ike 11 c# extension-methods casting
简化,我有这两种Extension方法:
public static class Extensions
{
public static string GetString(this Exception e)
{
return "Standard!!!";
}
public static string GetString(this TimeoutException e)
{
return "TimeOut!!!";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我使用它们的地方:
try
{
throw new TimeoutException();
}
catch (Exception e)
{
Type t = e.GetType(); //At debugging this a TimeoutException
Console.WriteLine(e.GetString()); //Prints: Standard
}
Run Code Online (Sandbox Code Playgroud)
我有更多的GetString()扩展.
我try{...}catch{...}变得越来越大,基本上我搜索方法将其缩短为1个捕获,根据异常的类型调用扩展.
有没有办法在运行时调用正确的扩展方法?
正如 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!!!";
}
}
Run Code Online (Sandbox Code Playgroud)
这应该能解决问题。
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |