反对自动属性的情况 [英] The case against automatic properties

查看:66
本文介绍了反对自动属性的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C#3.0自动属性-是否有用?

Possible Duplicate:
C# 3.0 Auto-Properties - useful or not?

我的老板和我经常争论使用自动属性的利弊.

My boss and I regularly argue about the benefits and disadvantages of using automatic properties.

public string Name { get; set; }

vs

private string name;

public string Name
{
    get { return this.name; }
    set { this.name = value; }
}


对于

我坚决赞成使用它们,因为我必须编写更少的代码,当以这种方式对所有字段进行编码时,我发现更容易理解该类,只是从长远来看节省了我很多时间(主要是因为我每次都写更少的代码).


For

I am strongly in favor of using them because I have to write less code, I find it easier to understand the class when all the fields are coded that way and just saves me a lot of time in the long run (mostly because I write a bit less code each time).

他认为它们违反了一些编程原理,因为字段应反映对象的状态,并且通过使用属性而不是具有属性的字段来访问对象,我在调试时会丢失该信息. (老板,如果您阅读了此书,但它不是您的意思,请随时发表评论;))

He argues that they break some programming principle because the fields should reflect the state of the object and by using a property instead of a field with a property to access it, I lose that information while debugging. (Boss if you read this and it's not exactly what you mean, feel free to comment ;))

每个人对此事有什么看法?

What's everyone's take on this matter?

注意::我已经查看了重复项,但它没有谈论反对要点,这是这个问题的重点.只是人们在说我爱他们"/我不在乎".

NOTE: I have looked at the duplicate and it doesn't talk about the against points which is the point of this question. It's just people saying "I love them"/"I don't care".

推荐答案

您如何放弃该信息?该属性反映的是对象的状态,而不是字段的状态-有很大的不同吗?

How do you give up that information? The property reflects the state of the object instead of the field - is it that big a difference?

我唯一想得到一个字段支持的情况是,在设置它(例如验证)时或者在我想要执行一种设计模式(例如缓存值或单例等)时需要做其他的逻辑.

The only time I want to have it backed by a field is if I need to do additional logic when setting it (ie: validation) or when I want to enforce a design pattern such as caching the value or singleton etc.

这篇关于反对自动属性的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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