在一个使用 C# 8 的项目中,我正在使用可空引用类型,并收到一个意外的(或至少是对我来说意外的)CS8629警告。
请注意,
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")}";
}
我决定使用 GetValueOrDefault()
作为解决方法,但我想知道如何向编译器证明如果检查了 singleContent
,x.DataInt
就不可能为空。请注意,
x.DataInt
的类型是 int?
。
x.DataInt!.Value
。 - canton7!
运算符的一个好案例。但是,你需要小心,以免在你使用它的两个当前位置之间意外覆盖singleContent
变量的值,因为!
运算符将无法捕获意图的变化。 - Lasse V. Karlsen