Tro*_*yvs 0 c# out c#-8.0 nullable-reference-types
我正在将一些代码从 C#5 转换为 C#8,在编译规则集中启用可空检查,
<Nullable>enable</Nullable>
Run Code Online (Sandbox Code Playgroud)
然后我遇到了这样的问题:
class Person
{
public int MI { get; set; } = 3;
}
class UseWeakReference
{
public static void Main(string [] args)
{
Person person = new Person();
WeakReference<Person> wr = new WeakReference<Person>(person);
wr.TryGetTarget(out Person p1); // doesn't compile
Console.WriteLine(p1);
}
}
Run Code Online (Sandbox Code Playgroud)
编译错误是:
CS8600: Converting null literal or possible null value to non-nullable type.
Run Code Online (Sandbox Code Playgroud)
这个编译错误的真正原因是什么,以及如何修复它?
您可以允许out参数为可能的空引用,并null在方法调用后将其与值进行比较
wr.TryGetTarget(out Person? p1);
if (p1 != null)
Console.WriteLine(p1);
Run Code Online (Sandbox Code Playgroud)
或者简单地检查方法的返回结果TryGetTarget:当它是 时true,p1不能是null
var result = wr.TryGetTarget(out Person? p1);
if (result)
Console.WriteLine(p1);
Run Code Online (Sandbox Code Playgroud)
编译器警告的原因是TryGetTarget这样实现的
public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target)
{
// Call the worker method that has more performant but less user friendly signature.
T o = this.Target;
target = o!;
return o != null;
}
Run Code Online (Sandbox Code Playgroud)
参数的可空性out根据返回值、根据[MaybeNullWhen(false), NotNullWhen(true)]属性来确定,并且不能在编译时确定,只能在运行时确定。
当您将其分配给不可为 null 的引用时,编译器会警告您可能出现的问题。检查返回结果或使用Person?似乎是一个正确的解决方案