【发布时间】:2018-07-29 16:14:01
【问题描述】:
我有一个Generic interface 声明Generic Method,如下所示。
public interface BaseInterface<T> where T: class
{
//This will not generate the compile time
//warning that the type parameter of method is same as interface
U Method1<U>(U u) where U : T;
}
现在我定义了一个新的Concrete类,继承了上面接口的一个closed constructed type。
public class DerivedClass : BaseInterface<string>
{
U BaseInterface<string>.Method1<U>(U u)
{
return "Some String";
}
}
在界面中,我使用了对类型参数U的约束为where U : T。我还使用了T is string 的封闭构造类型。那么在DerivedClass 中,为什么编译器不让我返回string?
错误:
错误 CS0266 无法将类型“字符串”隐式转换为“U”。存在显式转换(您是否缺少演员表?) GenericPractice
【问题讨论】:
-
为什么不用
U Method1<U>() where U : T;而只是做T Method1()? -
我希望 Method1 在类型参数上的工作与类的相同。
-
我现在稍微修改了接口定义。
-
想象一下你使用了 BaseInterface
-
另外,当 T 是一个字符串时,你期望 U 是什么?字符串被密封。为什么不返回 T?
标签: c# generics inheritance