为什么 C# 6.0 不允许在使用 Null 传播运算符时设置非 null 可为空结构的属性? [英] Why C# 6.0 doesn't let to set properties of a non-null nullable struct when using Null propagation operator?

查看:29
本文介绍了为什么 C# 6.0 不允许在使用 Null 传播运算符时设置非 null 可为空结构的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下代码:

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

但稍后当你这样做时:

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.

如果您只是想设置属性,那么您不需要 ? 和对象名称,?Nullable> 声明时使用类型,语法糖为:

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 传播运算符时设置非 null 可为空结构的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆