【发布时间】:2011-03-23 09:50:57
【问题描述】:
我正在查看this 问题,我很好奇为什么这个deos 不能编译。
鉴于此代码,谁能解释为什么对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'.
我有一种感觉,因为它对于任何实现 IChildB 并且不知道要使用哪种扩展方法的东西都是模棱两可的,但是错误消息并没有抱怨它的那一面,如果你删除IBase firstTry = a.Test(); 行然后它编译得很好..
【问题讨论】:
-
您的编译器错误与您发布的代码不匹配(测试与触摸)。请从您发布的 exact 代码中发布 exact 错误 - 否则我们将不知道您可能进行了哪些其他细微的更改。
-
另请参阅blogs.msdn.com/b/ericlippert/archive/2009/12/10/…,大约有一百人告诉我这是一个明智的规则,我错了。
标签: c# .net generics extension-methods