C# 3.0 自动属性——有用与否?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# 3.0 auto-properties — useful or not?
提问by Michael Stum
Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.
注意:这是在我开始使用 C# 时发布的。凭借 2014 年的知识,我真的可以说自动属性是 C# 语言中发生过的最好的事情之一。
I am used to create my properties in C# using a private and a public field:
我习惯于使用私有和公共字段在 C# 中创建我的属性:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Now, with .NET3.0, we got auto-properties:
现在,使用.NET3.0,我们获得了自动属性:
public string Title { get; set; }
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
我知道这更像是一个哲学/主观问题,但是除了为每个字段保存五行代码之外,是否有任何理由使用这些自动属性?我个人的抱怨是这些属性对我隐瞒了一些东西,而且我不是黑魔法的忠实粉丝。
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
事实上,隐藏的私有字段甚至没有出现在调试器中,考虑到 get/set 函数什么都不做,这是可以的。但是当我想真正实现一些 getter/setter 逻辑时,无论如何我都必须使用私有/公共对。
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
我看到了我节省了大量代码(一行对六行)的好处,而不会失去稍后更改 getter/setter 逻辑的能力,但是我已经可以通过简单地声明一个公共字段“公共字符串标题”来做到这一点,而不是{ get; 的需要;放; } 块,从而节省更多代码。
So, what am I missing here? Why would anyone actually want to use auto-properties?
那么,我在这里错过了什么?为什么会有人真正想要使用自动属性?
采纳答案by Jeff Atwood
We use them all the time in Stack Overflow.
我们一直在 Stack Overflow 中使用它们。
You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.
您可能还对Properties 与 Public Variables的讨论感兴趣。恕我直言,这真的是一种反应,为此目的,它很棒。
回答by Ray
I personally love auto-properties. What's wrong with saving the lines of code? If you want to do stuff in getters or setters, there's no problem to convert them to normal properties later on.
我个人喜欢自动属性。保存代码行有什么问题?如果您想在 getter 或 setter 中执行操作,稍后将它们转换为普通属性没有问题。
As you said you could use fields, and if you wanted to add logic to them later you'd convert them to properties. But this might present problems with any use of reflection (and possibly elsewhere?).
正如您所说,您可以使用字段,如果您想稍后向它们添加逻辑,您可以将它们转换为属性。但这可能会给反射的任何使用带来问题(也可能在其他地方?)。
Also the properties allow you to set different access levels for the getter and setter which you can't do with a field.
此外,这些属性允许您为 getter 和 setter 设置不同的访问级别,而这在字段中是无法做到的。
I guess it's the same as the var keyword. A matter of personal preference.
我想它与 var 关键字相同。个人喜好问题。
回答by lomaxx
The three big downsides to using fields instead of properties are:
使用字段而不是属性的三大缺点是:
- You can't databind to a field whereas you can to a property
- If you start off using a field, you can't later (easily) change them to a property
- There are some attributes that you can add to a property that you can't add to a field
- 您不能将数据绑定到字段,而可以绑定到属性
- 如果您开始使用一个字段,您以后不能(轻松地)将它们更改为一个属性
- 有一些属性可以添加到不能添加到字段的属性中
回答by Orion Edwards
I use auto-properties all the time. Before C#3 I couldn't be bothered with all the typing and just used public variables instead.
我一直在使用自动属性。在 C#3 之前,我不会被所有的打字所困扰,而是使用公共变量。
The only thing I miss is being able to do this:
我唯一想念的是能够做到这一点:
public string Name = "DefaultName";
You have to shift the defaults into your constructors with properties. tedious :-(
您必须将默认值转移到具有属性的构造函数中。乏味:-(
回答by Mike Stone
I think any construct that is intuitive AND reduces the lines of code is a big plus.
我认为任何直观并减少代码行的构造都是一个很大的优势。
Those kinds of features are what makes languages like Ruby so powerful (that and dynamic features, which also help reduce excess code).
正是这些特性使得像 Ruby 这样的语言如此强大(以及动态特性,这也有助于减少多余的代码)。
Ruby has had this all along as:
Ruby 一直是这样的:
attr_accessor :my_property
attr_reader :my_getter
attr_writer :my_setter
回答by David Wengier
The only problem I have with them is that they don't go far enough. The same release of the compiler that added automatic properties, added partial methods. Why they didnt put the two together is beyond me. A simple "partial On<PropertyName>Changed" would have made these things really really useful.
我对他们的唯一问题是他们走得还不够远。相同版本的编译器添加了自动属性,添加了部分方法。为什么他们没有把两者放在一起是我无法理解的。一个简单的“部分 On<PropertyName>Changed”会使这些东西真正有用。
回答by Keith
Yes, it does justsave code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.
是的,它只是保存代码。当您拥有大量内容时,阅读起来会轻松很多。它们编写起来更快,也更容易维护。保存代码始终是一个很好的目标。
You can set different scopes:
您可以设置不同的范围:
public string PropertyName { get; private set; }
So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection.
这样该属性只能在类内部更改。这并不是一成不变的,因为您仍然可以通过反射访问私有 setter。
As of C#6 you can also create true readonly
properties - i.e. immutable properties that cannot be changed outside of the constructor:
从 C#6 开始,您还可以创建真正的readonly
属性 - 即不能在构造函数之外更改的不可变属性:
public string PropertyName { get; }
public MyClass() { this.PropertyName = "whatever"; }
At compile time that will become:
在编译时将变成:
readonly string pName;
public string PropertyName { get { return this.pName; } }
public MyClass() { this.pName = "whatever"; }
In immutable classes with a lot of members this saves a lot of excess code.
在具有很多成员的不可变类中,这可以节省大量多余的代码。
回答by pbh101
One thing to note here is that, to my understanding, this is justsyntactic sugar on the C# 3.0 end, meaning that the IL generated by the compiler is the same. I agree about avoiding black magic, but all the same, fewer lines for the same thing is usually a good thing.
这里需要注意的一件事是,据我所知,这只是C# 3.0 端的语法糖,意味着编译器生成的 IL 是相同的。我同意避免使用黑魔法,但同样的,同一件事少用几行通常是件好事。
回答by ESV
In my opinion, you should always use auto-properties instead of public fields. That said, here's a compromise:
在我看来,您应该始终使用自动属性而不是公共字段。也就是说,这是一个妥协:
Start off with an internalfield using the naming convention you'd use for a property. When you first either
从使用属性命名约定的内部字段开始。当你第一次
- need access to the field from outside its assembly, or
- need to attach logic to a getter/setter
- 需要从其程序集外部访问该字段,或
- 需要将逻辑附加到 getter/setter
Do this:
做这个:
- rename the field
- make it private
- add a public property
- 重命名字段
- 将其设为私有
- 添加公共属性
Your client code won't need to change.
您的客户端代码不需要更改。
Someday, though, your system will grow and you'll decompose it into separate assemblies and multiple solutions. When that happens, any exposed fields will come back to haunt you because, as Jeff mentioned, changing a public field to a public property is a breaking API change.
但是,总有一天,您的系统会增长,您会将其分解为单独的程序集和多个解决方案。发生这种情况时,任何公开的字段都会再次困扰您,因为正如杰夫所说,将公共字段更改为公共属性是一个破坏性的 API 更改。
回答by ICR
Auto-properties are as much a black magic as anything else in C#. Once you think about it in terms of compiling down to IL rather than it being expanded to a normal C# property first it's a lot less black magic than a lot of other language constructs.
自动属性与 C# 中的其他任何东西一样都是黑魔法。一旦你从编译成 IL 的角度考虑它,而不是首先将其扩展为普通的 C# 属性,它就会比许多其他语言结构少很多黑魔法。