c# 类中字段属性设计

1、当把属性设计成private set时,表示在外部类中就不能对该属性赋值。如

public  class A
    {
        string pwd;
        public event EventHandler PasswordChanging;

        public string Pwd
        {
            get { return pwd; }
            private set
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new ArgumentException("password cannot be empty");
                }
                if (pwd != value)
                {
                    if (PasswordChanging != null) PasswordChanging(this, EventArgs.Empty);
                }
                pwd = value;
            }
        }

        void Test()
        {
            this.pwd = "abc";                 // 直接赋值,什么额外事情都不会发生
              this.Pwd = "efg";                 // 可以引发密码更改事件,可以进行校验
        }
    }

 引用CSDN

 

属性的设计,更新中....

相关文章:

  • 2022-12-23
  • 2021-12-19
  • 2020-10-20
  • 2021-08-25
  • 2021-12-26
  • 2021-12-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2022-03-04
相关资源
相似解决方案