【问题标题】:How can I force user to use methods to change the Class Fields , and do not change it directly? [duplicate]如何强制用户使用方法来更改 Class Fields ,而不是直接更改? [复制]
【发布时间】:2018-05-09 04:18:04
【问题描述】:

我是一名 VBA 开发人员,刚接触 C# 下面是我的员工类:

class Employee
{
   public string name;

   public Employee()
    {
       age = 0;
    }

    public void setName(string newName)
    {
        name = newName;
    }  
}

当我创建 Employeeclass 的对象时,我可以使用提供的方法来设置 name 的值

Employee E1 = new Employee();
E1.setName("Name 1");

或者我可以直接设置名称。

Employee E1 = new Employee();
E1.name = "Name 1"

重点是如何阻止用户直接/不调用我的方法来设置我的字段的值,如果你能告诉我如何有效地设置我的类字段的值。

【问题讨论】:

标签: c# oop


【解决方案1】:

只需使用属性而不是(公共)字段。

public class Employee
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            // Your setter-code here. Validation and stuff like that
            _name = value;
        }
    }
}

【讨论】:

    【解决方案2】:

    您应该定义私有成员。

    class Employee
    {
       private string name;
    
        public void setName(string newName)
        {
            name = newName;
        }  
    }
    

    注意:类的私有成员只能在类定义内访问,而公共成员可以通过使用其对象在类外访问。

    或者,简单地使用属性,

    class Employee
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
    

    使用属性,可以将Name设置为,

      Employee emp = new Employee();
      emp.Name = "suman";
    

    【讨论】:

      【解决方案3】:

      您想使用公共属性并将字段 private 设置为如下所示。你不需要一个单独的 setter 方法,就像你正在做的那样

      class Employee
      {
         private string name;
      
         public Employee()
          {
             age = 0;
          }
      
          public string Name
          {
            get {return name; }   
            set { name = value; }
          }  
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2013-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多