Skip to main content
 首页 » 编程设计

c#之在构造函数中使用私有(private)变量或属性

2024年02月06日12qq号

    class Person  
{ 
    private string fname; 
    private string lname; 
 
    public string F  
    { 
        get { return fname; } 
        set { fname = value; } 
    } 
 
    public string L 
    { 
        get { return lname; } 
        set { lname = value; } 
    } 
 
    public Person(string fname, string lname)  
    { 
        this.fname = fname; 
        this.lname = lname; 
    } 
} 

哪个更好,是在构造函数中使用属性,还是保留上面的属性?为什么?

附言我正在使用一个使用属性的函数,这就是我不使用自动属性的原因。

请您参考如下方法:

如果你想要一个不可变的类,这样做:

class Person  
{ 
    public string F { get; private set; } 
    public string L { get; private set; } 
 
    public Person(string f, string l)  
    { 
        F = f; 
        L = l; 
    } 
} 

对于一个可变类,这样做:

class Person  
{ 
    public string F { get; set; } 
    public string L { get; set; } 
} 

并像这样使用它:

Person p = new Person { L = "laugh", F = "fun" };