在分配的左侧使用空条件运算符 [英] Using the null-conditional operator on the left-hand side of an assignment

查看:84
本文介绍了在分配的左侧使用空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个页面,每个页面都有一个名为 Data 的属性。在另一页上,我像这样设置数据:

I have a few pages, each with a property named Data. On another page I'm setting this data like this:

if (MyPage1 != null)
    MyPage1.Data = this.data;
if (MyPage2 != null)
    MyPage2.Data = this.data;
if (MyPage3 != null)
    MyPage3.Data = this.data;

是否有可能在 MyPage上使用空条件运算符?我在想这样的事情:

Is there any possibility to use the null-conditional operator on MyPage? I'm thinking of something like this:

MyPage?.Data = this.data;

但是当我这样写时,出现以下错误:

But when I write it like this, I get the following error:


分配的左侧必须是变量,属性或索引器。

The left-hand side of an assignment must be a variable, property or indexer.

我知道这是因为 MyPage 可以为null,并且左侧不再是变量。

I know it's because MyPage could be null and the left-hand side wouldn't be a variable anymore.

不是我不能像已经拥有它那样使用它,而是我只想知道是否有可能在此上使用空条件运算符。

It's not that I cannot use it like I have it already but I just want to know if there's any possibility to use the null-conditional operator on this.

推荐答案

空传播运算符返回一个值。而且由于您必须在赋值的左侧有一个变量而不是一个值,所以您不能以这种方式使用它。

The null propagation operator returns a value. And since you must have a variable on the left hand side of an assignment, and not a value, you cannot use it in this way.

当然,您可以制作东西

Joachim Isaksson对您的问题的评论表明,另一种方法是应该管用。

Joachim Isaksson's comment on your question shows a different approach that should work.

这篇关于在分配的左侧使用空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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