为什么C#6.0不允许在使用Null传播运算符时设置非空可空结构的属性? [英] Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?
问题描述
假设我们有以下代码:
struct Article
{
public string Prop1 { get; set; }
}
Article? art = new Article();
art?.Prop1 = "Hi"; // compile-error
编译错误是
CS0131作业的左侧必须是变数,属性或索引。
CS0131 The left-hand side of an assignment must be a variable, property or indexer.
实际上 art?.Prop1
是一个属性,应该被认为是有效的赋值!
我没有看到任何问题,代码无效。
Actually art?.Prop1
is a property and should be considered as a valid assignment!
I don't see any problem with assignment to make this code invalid.
为什么C#6.0不允许设置一个非空的可空结构的属性?
或者,一行代码的任何建议使分配有效将不胜感激。
Why C# 6.0 doesn't let to set properties of a non-null nullable struct ?
Alternately any suggestion for one line code to make assignment valid would be appreciated.
推荐答案
此代码:
Article? art
将定义 Nullable< Article>
但后来当你这样做:
will define a Nullable<Article>
but later when you do:
art?.Prop1 = "Hi";
这意味着使用Null传播/条件运算符。
This will mean using Null propagation/conditional operator.
空传播/条件运算符用于访问属性,而不是设置它们。因此你不能使用它。
Null propagation/conditional operator is for accessing properties, not setting them. Hence you can't use it.
由于@Servy在注释中说,Null条件运算符的结果总是一个值,您不能为值分配值,因此错误。
As @Servy said in the comments, the result of Null conditional operator is always a value and you can't assign a value to a value, hence the error.
如果你只是想设置属性,那么你不需要?
code> 与 Nullable< T>
类型在声明时使用,这是语法糖:
If you are only trying to set the property then you don't need ?
with the object name, ?
with Nullable<T>
types is used at the time of declaration, which is syntactic sugar to:
Nullable<Article> art; //same as Article? art
这篇关于为什么C#6.0不允许在使用Null传播运算符时设置非空可空结构的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!