监听某些在类上更改的值

问题描述 投票:0回答:1

我希望在对象上每次更改某些值时都运行一种方法。

我想知道是否可以创建一个Custom属性,以在其值更改时添加到要触发我的方法的值。

Fx:

public class Program
{
    public static void Main()
    {
        A a = new A("Hello", true);
        a.text = "Goodbye";
        a.check = false;
    }
}
public class A{
   public string text {get; set;}
   [RunMyMethod]
   public bool check {get; set;}

   public A(string t, bool c){
       this.text = t;
       this.check = c;
   }
}

public class RunMyMethod : System.Attribute
{
}

我知道我只是去每个字段Set方法中添加一些东西,但是我想在上面实现它的类非常大,而且不是很漂亮。

c# custom-attributes
1个回答
0
投票

这就是我们为什么要这样做的原因!

因此,首先,更改

public bool check {get; set;}

to

private bool _check;

并定义用于设置此值的属性:

public bool Check
{
  get { return _check; }
  set
  {
    // here you can add your logic,
    // If this logic is common for every field, you
    // can wrap it in method and call it here.
    // Also here you can use variable named "value", which holds
    // value to be set.
    // At the end, set the value:
    _check = value;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.