C#自动属性 ​​- 为什么我要写"获得;设置;"? [英] C# Automatic Properties - Why Do I Have To Write "get; set;"?

查看:173
本文介绍了C#自动属性 ​​- 为什么我要写"获得;设置;"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果get和set在C#自动属性强制性的,为什么我费心指定获得;设置;在所有

If both get and set are compulsory in C# automatic properties, why do I have to bother specifying "get; set;" at all?

推荐答案

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

如果您没有指定 {搞定;设置;} 那么编译器将不知道这是否是一个字段或属性。
这是当他们看相同的编译器会将它们不同的重要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.

这篇关于C#自动属性 ​​- 为什么我要写"获得;设置;"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆