正确使用 C# 属性 [英] Correct use of C# properties

查看:21
本文介绍了正确使用 C# 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private List<Date> _dates;

public List<Date> Dates
{
    get { return _dates; }
    set { _dates = value; }
}

public List<Date> Dates
{
    get;        
    set;    
}

我一直使用前者,这是不正确还是不好的做法?我从来没有想过我可以只使用第二个选项.我确实喜欢让我的封装变量以下划线开头,这样我就可以将它们与方法参数区分开来.而我一直都是这样做的.

I have always used the former, is that incorrect or bad practice? It never occurred to me that I could just use the second option. I do like having my encapsulated variables to begin with an underscore so I can distinguish them from method parameters. And I've just always done it that way.

使用第一个选项是否可能会导致额外的 List 对象被实例化,然后整个 _dates 被替换为 value,还是比那更智能?

Is it possible that using the first option would result in an extra List<Date> object being instantiated and then the whole of _dates being replaced with value, or is it more intelligent than that?

还有,哪个是业界最突出的还是完全主观的?

Also, which is the most prominent in industry or is it totally subjective?

推荐答案

它们在内部编译形式上是等价的,只是在第二种形式中不能访问编译器生成的私有变量.

They are equivalent in the internal compiled form, except that you cannot access the compiler generated private variable in the second form.

从代码效率的角度来看,它们也是等价的,即时编译器通常直接访问私有变量,而无需调用访问函数的开销(在运行时环境检查可访问性等之后).

From a code efficiency point of view, they are equivalent as well, the just in time compiler normally directly accesses the private variable without the overhead of calling an access function (after the runtime environment has checked accessibility etc.).

从编码的角度来看,我更喜欢第二个版本,它更紧凑(少写,少读).

From a coding perspective, I prefer the second version which is more compact (less to write, less to read).

第二种语法是在 C# 3.0 中引入的.所以第一个变体会更兼容旧的编译器.

The second syntax was introduced in C# 3.0. So the first variant would be more compatible to old compilers.

这篇关于正确使用 C# 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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