c#设置私有变量的值

use*_*970 1 c# private getter-setter

我正在使用getter/setter属性来获取或设置变量我的代码工作正常如果我使用公共变量来设置值,因为我正在创建我的类的数组,但我只是想知道如何设置私有变量的值.我的代码是

public class Person
{
    //getter and setter for each variable
    private string _Name;
    public string Name
    {
        get { return _Name;}
        set { _Name= value; }
    }

    private int _Age;
    public int Age
    {
        get {return _Age;  }
        set  {  _Age= value;   }
    }  
        .... // other properties

    // Another Class 
    public void setValues (Person[] p,int i)
    {    p[i].Age= 30;
    }
Run Code Online (Sandbox Code Playgroud)

但是,如果我将我的set变量更改为private,如何设置变量?

    private int _Age;
    public int Age
    {
       get {return _Age;  }
       private  set  {  _Age= value;   }
    } 
Run Code Online (Sandbox Code Playgroud)

Man*_*eld 7

如果将set方法更改为private,则无法在类外设置该属性的值; 这是private关键字的重点.如果您想避免公开,我会考虑使用protectedinternal关键字.

或者,正如JNYRanger所说,你可以从构造函数中调用这个setter,这样你就可以在当前类的"外部"有效地设置该值.

例:

public class Person 
{    
    public int Age { get; private set; }

    public Person (int age) 
    {
        Age = age;
    }
}
Run Code Online (Sandbox Code Playgroud)