问题
In a C# 8 project, I am using nullable reference types and am getting an unexpected (or at least, unexpected to me) CS8629 warning,
bool singleContent = x.DataInt != null;
bool multiContent = x.DataNvarchar != null;
if (singleContent && multiContent)
{
throw new ArgumentException("Expected data to either associate a single content node or " +
"multiple content nodes, but both are associated.");
}
if (singleContent)
{
var copy = x.DataInt.Value; // CS8629 here
newPropertyData.DataNvarchar = $"umb://{type.UdiType}/{Nodes[copy].UniqueId.ToString("N")}";
}
I've decided to use GetValueOrDefault()
as a workaround, but I'd like to know how to prove to the compiler that x.DataInt
can't be null if singleContent
is checked.
Note that the type of x.DataInt
is int?
.
回答1:
This is just a temporary answer until Julien Couvreur, one of the designers of nullable reference types posts the definitive answer (nagging). I'm posting this here because the question will be asked again once C# 8 is released.
As Julien answers in 3 Github issues #34800 , #37032 and #36149 this is a known limitation of the C# 8 analyzer that's out of scope for C# 8.
This requires alias analysis which (just guessing here) means that the analyzer will be able to analyze aliased expressions, ie expressions whose results are "hidden" behind temporary variables (possibly parameters too?).
Perhaps we can ask him or Mads Torgersen online when .NET Core 3 is released during .NET Conf 2019 about a release date (totally not nagging)
来源:https://stackoverflow.com/questions/57432944/nullable-reference-types-unexpected-cs8629-nullable-value-type-may-be-null-with