c# - 使用派生类型调用扩展方法的重载
问题描述
简化,我有这两种Extension
方法:
public static class Extensions
{
public static string GetString(this Exception e)
{
return "Standard!!!";
}
public static string GetString(this TimeoutException e)
{
return "TimeOut!!!";
}
}
这是我使用它们的地方:
try
{
throw new TimeoutException();
}
catch (Exception e)
{
Type t = e.GetType(); //At debugging this a TimeoutException
Console.WriteLine(e.GetString()); //Prints: Standard
}
我有更多的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!!!";
}
}
这应该是诀窍。