在赋值的左侧使用空条件运算符

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

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

有没有可能在MyPage上使用空条件运算符? 我在考虑这样的事情:

 MyPage?.Data = this.data; 

但是当我这样写时,我收到以下错误:

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

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

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

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

当然,你可以通过使用tenary运算符来缩短时间,但另一方面,这并没有真正帮助可读性方面。

Joachim Isaksson对您的问题的评论显示了一种应该有效的不同方法。

正如Joachim Isaksson在评论中建议的那样,我现在有一个方法SetData(Data data)并使用它如下:

 MyPage1?.SetData(this.data); MyPage2?.SetData(this.data); MyPage3?.SetData(this.data); 

试试这个将你的所有页面添加到myPageList。

 IEnumerable myPageList; foreach(MyPage myPage in myPageList) { if (myPage != null) myPage.Data = this.data; } 

我想出了以下扩展,

 public static class ObjectExtensions { public static void SetValue(this object @object, string propertyName, TValue value) { var property = @object.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); if (property?.CanWrite == true) property.SetValue(@object, value, null); } } 

这可以称为全球; 这仅适用于公共财产。

 myObject?.SetValue("MyProperty", new SomeObject()); 

以下改进版本适用于任何事物,

 public static void SetValue(this TObject @object, Action assignment) { assignment(@object); } 

也可以在全球范围内调用,

 myObject?.SetValue(i => i.MyProperty = new SomeObject()); 

但扩展名有点误导,因为Action并不仅仅要求转让。

派对的时间比较晚,但我带着类似的问题来到这篇文章。 我采用了SetValue方法的想法并创建了一个通用的扩展方法,如下所示:

 ///  /// Similar to save navigation operator, but for assignment. Useful for += and -= event handlers. /// If  is null, then  is not performed and false is returned. /// If  is not null, then  is performed and true is returned. ///  public static bool SafeAssign(this T obj , Action action ) where T : class { if (obj is null) return false; action.Invoke(obj); return true; } 

示例用法,用于附加和分离事件处理程序:

 public void Attach() => _control.SafeAssign(c => c.MouseDown += Drag); public void Detach() => _control.SafeAssign(c => c.MouseDown-= Drag); 

希望有人发现它有用:)

通用的SetValue扩展方法(但仅适用于ref属性)将是:

  public static void SetValue(this T property, T value) { property = value; } 

并将使用像

 ButtonOrNull?.Visibility.SetValue(Visibility.Hidden);