C#允许运算符不一致

  • 本文关键字:不一致 运算符 c#
  • 更新时间 :
  • 英文 :


在使用C#9.0时,我注意到一个奇怪的不一致:

string notNull = "Hello";
string? nullable = null;
notNull = nullable!; // works just fine
Guid notNull = Guid.Empty;
Guid? nullable = null;
// throws a compiler error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'.
// An explicit conversion exists (are you missing a cast?)
notNull = nullable!;
notNull = nullable.Value; // works just fine

为什么会出现这种情况?我的理解是,允许null的运算符!与在Nullable<T>中包装类型相同。我不确定为什么零容忍操作符会在一种情况下工作而不是在另一种情况。Guid是一个结构类型,所以我想它可能与此有关。我在C#文档中找不到任何关于这方面的内容。

是的,因为string是引用(class(类型,而Guid是值(struct(类型。在C#的早期版本中,引用类型总是可以为null,因此出于向后兼容性的目的,可以容忍这种隐式转换。

有关详细信息,请参阅Microsoft关于可为null的引用类型的文档。

最新更新