【问题标题】:Listen to certain values changed on Class [duplicate]收听类上更改的某些值[重复]
【发布时间】:2020-05-30 02:59:33
【问题描述】:

我想运行一个方法,每次在对象上更改某些值时。

我想知道是否可以创建一个自定义属性来添加到我想要触发我的方法的值,当它们的值发生变化时。

效果:

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】:

这就是我们有字段的原因!

所以,首先,改变

public bool check {get; set;}

到

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;
  }
}

【讨论】:

  • 我认为 OP 已经考虑过这种方法:“我知道我只是简单地向每个字段 Set 方法添加一些东西,但是我想要实现它的类相当庞大,而且不会很漂亮。”
  • @MatthewWatson 但在我看来它可能非常漂亮并试图说服 OP :)
  • 完全忽略了问题的属性部分,尽管这似乎是 OP 的真正目标。在这个问题之后实际上是可能的:stackoverflow.com/questions/25200516/…
猜你喜欢
  • 1970-01-01
  • 2012-06-01
  • 2014-01-12
  • 2021-12-31
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
相关资源
最近更新 更多