简体   繁体   English

如何在 C# 中覆盖可为空的带注释的泛型方法?

[英]How do you override a nullable annotated generic method in C#?

I am trying to add nullability support to parts of an existing code base.我正在尝试向现有代码库的部分添加可空性支持。 One area that has me stumped is how to override a generic method when the return value is nullable annotated.让我感到困惑的一个领域是当返回值是可为空注释时如何覆盖泛型方法。

#nullable enable
public class Stuff<T> {}

public abstract class Base {
    public virtual Stuff<T?>? MakeStuff<T>() => null;
    
    public Stuff<T?>? MakeStuff2<T>() => null;  
}


public abstract class Derived : Base {
    public override  Stuff<T?>? MakeStuff<T>() => base.MakeStuff<T>();
}

This results in a pair of error messages that don't quite make sense to me:这会产生一对对我来说不太有意义的错误消息:

Compilation error (line 26, col 29): 'Derived.MakeStuff()': return type must be 'Stuff<T?>' to match overridden member 'Base.MakeStuff()'编译错误(第 26 行,第 29 行):“Derived.MakeStuff()”:返回类型必须是“Stuff<T?>”以匹配覆盖的成员“Base.MakeStuff()”

Compilation error (line 26, col 29): The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'编译错误(第 26 行,第 29 行):类型“T”必须是不可为空的值类型,才能将其用作泛型类型或方法“Nullable”中的参数“T”

This all works when nullable is not enabled.当未启用 nullable 时,这一切都有效。

Thanks to Emanuel who pointed me in the right direction.感谢伊曼纽尔为我指明了正确的方向。

The answer is to use the where T:default constraint which solves the issue in C#9 and above.答案是使用 where T:default 约束来解决 C#9 及更高版本中的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM