且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#自动属性 ​​- 为什么我要写"获得;设置;"?

更新时间:2023-02-15 20:52:46

错误:属性或索引器不可能会作为传出或引用参数传递>

如果您没有指定 {搞定;设置;} 那么编译器将不知道这是否是一个字段或属性。
这是当他们看相同的编译器会将它们不同的重要becasue。例如叫InitAnInt对房地产引发错误

If you didn't specify {get; set;} then the compiler wouldn't know if it's a field or a property. This is important becasue while they "look" identical the compiler treats them differently. e.g. Calling "InitAnInt" on the property raises an error.

class Test
{
    public int n;
    public int i { get; set; }
    public void InitAnInt(out int p)
    {
        p = 100;
    }
    public Test()
    {
        InitAnInt(out n); // This is OK
        InitAnInt(out i); // ERROR: A property or indexer may not be passed 
                          // as an out or ref parameter
    }
}

您不应创建公共字段/类上的变量,你永远不知道什么时候你会想改变它有GET和放大器; set访问,然后你不知道你要什么样的代码打破,特别是如果你有客户对你的API程序。

You shouldn't create public fields/Variables on classes, you never know when you'll want to change it to have get & set accessors, and then you don't know what code you're going to break, especially if you have clients that program against your API.

你也可以有不同的访问修饰符对于GET和放大器;集,例如{得到; 私人集;}使得到公众和设定私有的声明类。

Also you can have different access modifiers for the get & set, e.g. {get; private set;} makes the get public and the the set private to the declaring class.