c# - 为什么我不能像这样使用空合并运算符?

标签 c# .net guid

根据 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/

相关文章:

.net - 为什么首先需要 GUID 属性?

c# - 存储在 oracle 中的 GUID/RAW 几乎匹配,除了最后 4 个字符

c# - Wpf 应用程序——如何保存和加载应用程序所在的屏幕

c# - 使用 UNC 路径运行 exe 时,Microsoft.Practices.EnterpriseLibrary 出现部分受信任的调用者错误?

c# - .NET 核心 MvcHtmlString(TextboxFor, LabelFor).ToString() 错误

.NET --- 文本框控件 - 等待用户完成输入

.net - 如何通过仅编写一次来在客户端和服务器之间共享域类和业务规则,就像在 RIA 服务中一样

c# - 如何验证 GUID 是一个 GUID

c# - 当用户开始输入 wpf 时启用按钮

c# - 多次调用 ToList 会影响性能吗?