我在看this问题,我很好奇为什么这deosn't编译。扩展方法与泛型
鉴于此代码,任何人都可以解释为什么IBase.Test()
的调用不解析为正确的扩展方法?
public interface IBase { }
public interface IChildA : IBase { }
public interface IChildB : IBase { }
public static class BaseExtensions
{
public static IBase Test(this IBase self) { return self; }
public static T Test<T>(this T self) where T : IChildB { return self; }
}
public static class TestClass
{
public static void Test()
{
IChildA a = null; //Yeh i know its null but just testing for compile here..
IBase firstTry = a.Test(); //Cannot resolve to BaseExtensions.Test(this IBase obj)
IBase secondTry = ((IBase)a).Test(); //Resolves to BaseExtensions.Test(this IBase obj)
IChildB b = null;
IChildB touchedB = b.Test();
}
}
我得到的错误是
Error 166 The type 'IChildA' cannot be used as type parameter 'T' in the generic type or method 'BaseExtensions.Test<T>(T)'. There is no implicit reference conversion from 'IChildA' to 'IChildB'.
我有一种感觉,那是因为这将是ambigous对于任何实现IChildB
和不知道使用哪种扩展方法,但错误消息不会呻吟它的一面,如果你删除IBase firstTry = a.Test();
线,那么它编译罚款..
您的编译器错误与您发布的代码不符(Test vs Touch)。请发布您发布的*精确*代码的*确切*错误 - 否则我们不会知道您可能做出的其他细微更改。 – 2011-03-23 09:55:07
道歉..固定 – 2011-03-23 09:56:37
另请参阅http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx大约一百人告诉我,我错了,这是一个明智的规则。 – 2013-09-23 21:33:14