使用派生类型调用扩展方法的重载

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个捕获,根据异常的类型调用扩展.

有没有办法在运行时调用正确的扩展方法?

Ale*_*ria 4

正如 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)

这应该能解决问题。

  • 我在这里看到的唯一问题是与此代码交互的每个人都必须理解“(dynamic)e”。我会写一个很好的、很长的注释来解释这段代码的实际作用。 (2认同)