通用方法,使用T:base.调用其他方法时,为什么不认为T是具体类型?

Olt*_*nix 3 c# generics

我想知道我在这里失踪了什么.在调试时我将e视为SpecificException的一个实例,但是方法调用与具有基本Exception的签名匹配.怎么会?我可以在不添加LogException方法中的类型检查的情况下解决这个问题吗?

public string LogException<T>(T e)
        where T : Exception
{
    string errorMsg = e.ToString();
    errorMsg += Details(e);
    return errorMsg;
}

public string Details(Exception exception)
{
     return "foo";
}

public string Details(SpecificException exception)
{
     return "bar";
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 8

重载解析在编译时发生.在编译时,编译器不可能知道的运行时类型e.它只知道它eException由它衍生的类型或类型.
它不知道具体类型,因此唯一正确的重载是for Exception.

为了实现您的目标,您可以通过dynamic关键字使用DLR :

errorMsg += Details((dynamic)e);
Run Code Online (Sandbox Code Playgroud)

这会将重载决策移动到运行时,并且在那个时间点,实际的类型e是已知的,因此它可以选择最匹配它的过载.

  • 谢谢,无论是解释还是解决方案. (2认同)