【问题标题】:Call method/execute piece of code using Property attribute使用 Property 属性调用方法/执行一段代码
【发布时间】:2014-04-15 04:54:45
【问题描述】:

只是想知道是否可以使用属性属性调用方法。基本上,我想在任何公共属性更改时设置实体的状态。

就像我们有以下代码

public class Contact : EntityBase
{
    [NotifyChange]
    public string FirstName { get; set; }

    private void ChangeState()
    {
       EntityState = EntityState.Modified;
    }
}

当我们打电话时

var c = new Contact();
c.FirstName = "John";

在FirstName设置值之前(或之后)调用EntityState()函数。

有什么想法吗?

【问题讨论】:

    标签: c# attributes


    【解决方案1】:

    如果把属性改写成这样会简单很多:

    public class Contact : EntityBase
    {
    
        private string _firstName;
    
        [NotifyChange]
        public string FirstName
        {
            get
            {
                return _firstName;
            }
            set
            {
                ChangeState();
                _firstName = value;
            }
        }
    
        private void ChangeState()
        {
           EntityState = EntityState.Modified;
        }
    }
    

    【讨论】:

    • 我认为属性[NotifyChange]是一些没有意义的伪代码。
    • 我也是这么想的,但是因为我不知道确切的用途,所以把它放在那里。从语义上讲,使用该属性是没有意义的。
    • 我已经意识到这一点(对于上面的示例,我们不需要 NotifyChange 属性,因为它可以调用 ChangeState 函数)但是在许多类中,我有超过 20 个属性,并且每次声明私有变量并使用它来设置和获取属性是太多的工作。我只是在想一些聪明的方法来跟踪财产变化。如果什么都不可能,那么我没有其他改变,只能使用你提到的方式。
    • @ParthPatel 在这种情况下,有很多重构工具可以让生活变得轻松。
    • @Hamlet Hakobyan,重构工具之类的?
    【解决方案2】:

    试试这个:

    public class Contact : EntityBase
    {
        private string _firstName;
        public string FirstName
        {
            get {return _firstName}
            set
              {
                  _firstName = value;
                  EntityState(); // maybe here must by ChangeState()
              }
        }
    
        private void ChangeState()
        {
           EntityState = EntityState.Modified;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 2019-03-03
      • 1970-01-01
      • 2015-02-20
      • 2012-01-27
      • 2012-10-24
      • 2010-11-11
      • 2018-06-23
      • 2012-11-05
      相关资源
      最近更新 更多