简体   繁体   English

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

[英]Why can't I use the null-coalescing operator like this?

According to MSDN :根据MSDN

The ??这 ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types.运算符称为空合并运算符,用于为可空值类型或引用类型定义默认值。

But when I run the code below:但是当我运行下面的代码时:

Guid test;
Guid otherGuid = test ?? Guid.NewGuid();

I get the error:我收到错误:

Operator '??'操作员 '??' cannot be applied to operands of type 'System.Guid' and 'System.Guid'不能应用于“System.Guid”和“System.Guid”类型的操作数

I thought Guid was a reference type.我认为 Guid 是一种引用类型。 Is that not the case?不是这样吗? Could someone explain to my why this does not work?有人可以向我解释为什么这不起作用吗?

Guid is not a reference type, its a value type , you can't assign it null and that is why you can't check it with ?? Guid不是引用类型,它是一个值类型,您不能将其分配为 null,这就是您不能用??检查它的原因。

Following line will give you error.以下行会给你错误。

Cannot convert null to 'System.Guid' because it is a non-nullable value type无法将 null 转换为“System.Guid”,因为它是不可为 null 的值类型

Guid test = null;

You may use Nullable您可以使用Nullable

Nullable<Guid> test = null;
Guid otherGuid = test ?? Guid.NewGuid();

Or short form或简写

Guid? test = null;
Guid otherGuid = test ?? Guid.NewGuid();

Guid is a struct and not a class, and can thus not be null. Guid是结构体而不是类,因此不能为空。

For this to work, you could do something like this:为此,您可以执行以下操作:

Guid? nullableGuid = null;
/* At some point nullableGuid is perhaps assigned... */
Guid otherGuid = nullableGuid ?? Guid.NewGuid();

GUID is a structure. GUID 是一种结构。 http://msdn.microsoft.com/en-us/library/system.guid.aspx http://msdn.microsoft.com/en-us/library/system.guid.aspx

Try using Guid.Empty to do the check.尝试使用Guid.Empty进行检查。

Guid otherGuid = test == Guid.Empty ? Guid.NewGuid() : test;

As others have said, Guid is a value type and not a reference type, see here for a more in-depth explanation about the difference between the two.正如其他人所说,Guid 是值类型而不是引用类型,有关两者之间差异的更深入解释,请参见此处 You'd have two options in your scenario.在您的场景中,您有两种选择。

  1. Coalescence operator:合并运算符:
Guid? guid = null;
otherGuid = guid ?? Guid.NewGuid();
  1. default comparison default比较
otherGuid = guid == default ? Guid.NewGuid() : guid;

In the second option you could also guse Guid.Empty , but using the default keyword would be better practice.在第二个选项中,您也可以使用Guid.Empty ,但使用default关键字会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM