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

麦克风

简化后,我有以下两种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!!!";
    }
}

这应该可以解决问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章