C#零原谅运算符不一致性
在使用C#9.0时,我注意到一种奇怪的不一致性:C#零原谅运算符不一致性,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.
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的中相同。我不确定为什么空原谅运算符在一种情况下比在另一种情况下更有效Guid
是一种结构类型,所以我想它可能与此有关。我在C#文档中找不到关于此的任何内容。是的,这是因为string
是引用(class
)类型,而Guid
是值(struct
)类型。在以前的C#版本中,引用类型总是可以为空的,因此出于向后兼容的目的,允许进行此类隐式转换
有关更多信息,请参阅。,这很有意义。所以,在我看来,引用类型可能会被更改为?运算符,但这不会将它们包装在可为null的文件中,因为它们在以前版本的C#中已经可以为null,而不能为null的值类型需要包装在可为null的文件中。这是正确的吗?@widavies:yes,null
是其中T:struct
。它仅适用于属于结构的Ts。在Tref:class
中没有可为null的我的理解是,可以原谅null的操作符!与将类型包装为可空的类型相同。
这是错误的理解。