【发布时间】:2020-03-06 14:35:25
【问题描述】:
我正在将一些代码从 C#5 转换为 C#8,在编译规则集中启用可空检查,
<Nullable>enable</Nullable>
然后我遇到了这样的问题:
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);
}
}
编译错误为:
CS8600: Converting null literal or possible null value to non-nullable type.
这个编译错误的真正原因是什么,以及如何解决它?
【问题讨论】:
-
wr.TryGetValue(out p1);
-
@HirasawaYui:由于 C#7 已经可以在方法的参数中声明变量:docs.microsoft.com/en-us/dotnet/csharp/whats-new/…
标签: c# out c#-8.0 nullable-reference-types