相互更新的属性 [英] Properties that update each other

查看:59
本文介绍了相互更新的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,在一些 C# 代码中,我有一些类似于这两个属性的东西:

So, in some C# code, I have something similar to the two properties:

private string _foo;
private string _bar;

public Foo
{
   get;
   set {
      _foo = value;
      Bar = _foo.Substring(3, 5);
   }
}

public Bar
{
   get;
   set {
      _bar = value;
      Foo = "XXX" + _bar;
   }
}

问题:C# 属性是否会受到循环引用/更新的影响,就像这个例子会导致的那样?

Question: Are C# properties subject to circular references/updates, like this example would seem to cause?

推荐答案

可以通过直接更新隐藏字段来避免死循环,像这样:

You can avoid the infinite loop by updating the hidden field directly, like this:

private string _foo;
private string _bar;

public string Foo
{
   get { return _foo; }
   set {
      _foo = value;
      _bar = _foo.Substring(3, 5);
   }
}

public string Bar
{
   get { return _bar; }
   set {
      _bar = value;
      _foo = "XXX" + _bar;
   }
}

这将绕过其他属性的 setter,从而消除循环.

This will bypass the other property's setter, which eliminates the loop.

但是...这通常会导致以后的维护问题.就我个人而言,我会尝试寻找替代设计.

But... this generally causes maintenance headaches later on. Personally, I'd try to find an alternative design.

这篇关于相互更新的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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