gpt4 book ai didi

c# - 在 C# 中确定引用类型的可空性时,何时应使用 NullabilityInfo.ReadState 与 NullabilityInfo.WriteState?

转载 作者:行者123 更新时间:2023-12-05 04:30:08 24 4
gpt4 key购买 nike

随着C#引入可空引用类型,System.Reflection库中引入了NullabilityInfoContextNullabilityInfo,让我们可以看到属性、参数等的可空性

许多文档和社区答案都给出了这样的例子:

NullabilityInfoContext context = new();
var nullabilityInfo = context.Create(myPropertyInfo);

Console.WriteLine(nullabilityInfo.ReadState); // Nullable
Console.WriteLine(nullabilityInfo.WriteState); // Nullable

但这实际上并没有解释,在真实场景中,何时应该根据 ReadState 属性或 WriteState 属性来确定可空性。为什么它们甚至不同?是否存在 WriteState 为 Nullable 而 ReadState 为 NonNullable 或反之亦然的情况?

也许我遗漏了什么,但据我所知,当您使用 ? 指定可为 null 的引用类型时,它在读写上下文中是否为 null?

最佳答案

as far as I can tell, when you specify a nullable reference type with?, it is nullable in the context of both reading and writing

不,这是一个例子。所以我不会依赖其中之一。我也相信有一种方法可以改变是否只对公众进行评估,但我不喜欢这个功能,所以我不使用它(不是设计,实现)。

class Example
{
public string? Read { get; }
public string? Write { set => value = null; }
}

static void Main()
{
NullabilityInfoContext context = new();
var write = typeof(Example).GetProperty("Write");
var read = typeof(Example).GetProperty("Read");
var writeInfo = context.Create(write);
var readInfo = context.Create(read);
Console.WriteLine(writeInfo.ReadState);
Console.WriteLine(writeInfo.WriteState);
Console.WriteLine(readInfo.ReadState);
Console.WriteLine(readInfo.WriteState);
}

输出:

Unknown

Nullable

Nullable

Unknown

关于c# - 在 C# 中确定引用类型的可空性时,何时应使用 NullabilityInfo.ReadState 与 NullabilityInfo.WriteState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72133882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com