根据 MSDN :
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types.
但是当我运行下面的代码时:
Guid test;
Guid otherGuid = test ?? Guid.NewGuid();
我得到错误:
Operator '??' cannot be applied to operands of type 'System.Guid' and 'System.Guid'
我以为 Guid 是引用类型。不是这样吗?有人可以向我解释为什么这不起作用吗?
最佳答案
Guid
不是引用类型,它是值类型,您不能将其赋值为 null,这就是为什么您不能使用 ??
下一行会给你错误。
Cannot convert null to 'System.Guid' because it is a non-nullable value type
Guid test = null;
您可以使用 Nullable
Nullable<Guid> test = null;
Guid otherGuid = test ?? Guid.NewGuid();
或简称
Guid? test = null;
Guid otherGuid = test ?? Guid.NewGuid();
关于c# - 为什么我不能像这样使用空合并运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12312037/