[英]C# override base generic method cannot cast T to T?
Trying to override a method that returns the generic type.试图重写返回泛型类型的方法。
The compiler error is:编译器错误是:
CS0266 cannot implicit convert type 'T' to 'T?'.
Simple example:简单的例子:
public class Base
{
public virtual T? Method<T>()
{
return default;
}
}
public class Class : Base
{
public override T? Method<T>()
{
return base.Method<T>();
}
}
I understand that this is because the base method lacks a class constraint, but I am calling to the base method so there shouldn't be any conversion happening, right?我知道这是因为基本方法缺少 class 约束,但我正在调用基本方法,所以不应该发生任何转换,对吧?
Thank you @lidqy, that article helped a lot.谢谢@lidqy,那篇文章很有帮助。 Found I could do this to get it to compile.
发现我可以这样做来编译它。
public class Base {
public virtual T? Method<T>() {
return default;
}
}
public class Class : Base {
[return: System.Diagnostics.CodeAnalysis.MaybeNull()]
public override T Method<T>() {
return base.Method<T>();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.