Ric*_*end 2 .net c# generics extension-methods
我正在看这个问题,我很好奇为什么这个不能编译.
鉴于此代码,任何人都可以解释为什么调用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
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();行,那么它编译得很好. .
| 归档时间: |
|
| 查看次数: |
1990 次 |
| 最近记录: |