[英]Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?
Assume we have following code : 假设我们有以下代码:
struct Article
{
public string Prop1 { get; set; }
}
Article? art = new Article();
art?.Prop1 = "Hi"; // compile-error
The compile error is 编译错误是
CS0131 The left-hand side of an assignment must be a variable, property or indexer.
CS0131赋值的左侧必须是变量,属性或索引器。
Actually art?.Prop1
is a property and should be considered as a valid assignment! art?.Prop1
是一个属性,应该被认为是一个有效的任务!
I don't see any problem with assignment to make this code invalid. 我没有看到任何分配使这段代码无效的问题。
Why C# 6.0 doesn't let to set properties of a non-null nullable struct ? 为什么C#6.0不允许设置非null可空结构的属性?
Alternately any suggestion for one line code to make assignment valid would be appreciated. 或者,任何建议一个行代码使分配有效将不胜感激。
This code: 这段代码:
Article? art
will define a Nullable<Article>
but later when you do: 将定义一个
Nullable<Article>
但稍后当你这样做:
art?.Prop1 = "Hi";
This will mean using Null propagation/conditional operator. 这将意味着使用Null传播/条件运算符。
Null propagation/conditional operator is for accessing properties, not setting them. 空传播/条件运算符用于访问属性,而不是设置它们。 Hence you can't use it.
因此你不能使用它。
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. 正如@Servy在评论中所说,Null条件运算符的结果始终是一个值,您无法为值赋值,因此也就是错误。
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<T>
类型,这是语法糖:
Nullable<Article> art; //same as Article? art
Article? art
Article? art
is a shortcut for Nullable<Article> art
To assign property you need to access .Value
field of Nullable<T>
. Article? art
是一条捷径Nullable<Article> art
要指派你需要访问财产.Value
领域Nullable<T>
In general case you need to ensure art is not null: 一般情况下,您需要确保艺术不是空的:
if (art.HasValue)
{
art.Value.Prop1 = "Hi";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.