简体   繁体   English

C# 有没有办法在 T 上放置 Null 条件运算符(?)?

[英]C# Is there a way to put a Null-conditional operator (?) on T?

I have an interface<T> .我有一个interface<T> This interface has a method Compare(T x, T y) .这个接口有一个方法Compare(T x, T y)

  • x can never be null . x永远不能是null
  • y has a large chance of being null . y很有可能是null

I want to make this clear by using the Null-conditional operator ?我想通过使用 Null 条件运算符来明确这一点? on y : Compare(T x, T? y) .y上: Compare(T x, T? y)

Is this possible and from what version of C#?这可能吗?来自 C# 的哪个版本?

EDIT:编辑:

T can be a reference type and a value type. T可以是引用类型和值类型。

I found the answer in a document suggested by @PanagiotisKanavos:我在@PanagiotisKanavos 建议的文档中找到了答案:

https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references#generics https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references#generics

In C# 8.0, using T?在 C# 8.0 中,使用T? without constraining T to be a struct or a class did not compile.没有将T限制为structclass没有编译。 That enabled the compiler to interpret T?这使编译器能够解释T? clearly.清楚地。 That restriction was removed in C# 9.0, by defining the following rules for an unconstrained type parameter T :在 C# 9.0 中,通过为不受约束的类型参数T定义以下规则,删除了该限制:

  • If the type argument for T is a reference type, T?如果T的类型参数是引用类型, T? references the corresponding nullable reference type.引用相应的可为空的引用类型。 For example, if T is a string , then T?例如,如果T是一个string ,那么T? is a string?是一个string? . .

  • If the type argument for T is a value type, T?如果T的类型参数是值类型, T? references the same value type, T .引用相同的值类型T For example, if T is an int , the T?例如,如果Tint ,则T? is also an int .也是一个int

  • If the type argument for T is a nullable reference type, T?如果T的类型参数是可为空的引用类型,则T? references that same nullable reference type.引用相同的可为空引用类型。 For example, if T is a string?例如,如果T是一个string? , then T? ,那么T? is also a string?也是一个string? . .

  • If the type argument for T is a nullable value type, T?如果T的类型参数是可空值类型, T? references that same nullable value type.引用相同的可为空值类型。 For example, if T is a int?例如,如果Tint? , then T? ,那么T? is also a int?也是一个int? . .

For my question, this means I need to constrain T to a class, since I am on C#8.对于我的问题,这意味着我需要将T限制为 class,因为我使用的是 C#8。

Given that till this answer is written, it's not mentioned that if there is a condition on T like this鉴于在写完这个答案之前,没有提到如果T上存在这样的条件

public interface IDoWork<T> : where T: ???
{...}

we'll assume it to be a reference type我们假设它是一个引用类型

Now that it's assumed that T is a reference type then you should do this现在假设T是一个引用类型,那么你应该这样做

public int Compare(T x, T y)
{

    if (y == null)
        //Take decision accordingly.
    else
        //Take decision accordingly.
}

Compare methods do not take parameters as nullable types.比较方法不将参数作为可空类型。 They take pure instances and then inside the method decide according to the expected behaviour.它们采用纯实例,然后在方法内部根据预期的行为做出决定。

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

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