C# 属性与方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/601621/
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
Properties vs Methods
提问by Trumpi
Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?
快速提问:什么时候决定使用属性(在 C# 中),什么时候决定使用方法?
We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:
我们正忙于进行这场辩论,并发现了一些值得商榷的地方,我们应该使用属性还是方法。一个例子是这样的:
public void SetLabel(string text)
{
Label.Text = text;
}
In the example, Label
is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.
在示例中,Label
是 ASPX 页上的控件。是否有一个原则可以决定(在这种情况下)是将其作为方法还是属性。
I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.
我会接受最一般和最全面的答案,但这也涉及我给出的例子。
采纳答案by Ken Browning
From the Choosing Between Properties and Methodssection of Design Guidelines for Developing Class Libraries:
从“开发类库的设计指南”的“在属性和方法之间进行选择”部分:
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.
一般来说,方法代表动作,属性代表数据。属性旨在像字段一样使用,这意味着属性不应在计算上复杂或产生副作用。如果不违反以下准则,请考虑使用属性而不是方法,因为经验不足的开发人员会发现属性更易于使用。
回答by cletus
Yes, if all you're doing is getting and setting, use a property.
是的,如果您所做的只是获取和设置,请使用属性。
If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.
如果您正在做一些可能影响多个数据成员的复杂事情,那么使用一种方法更合适。或者,如果您的 getter 接受参数或您的 setter 接受多个值参数。
In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how youdo it (or how your team does it).
中间是一个灰色区域,这里的线条可能有点模糊。没有硬性规定,不同的人有时会不同意某物应该是属性还是方法。重要的是要(相对)与您的工作方式(或您的团队的工作方式)保持一致。
They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.
它们在很大程度上是可互换的,但一个属性向用户表明实现相对“简单”。哦,语法更简洁一些。
Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property.
一般而言,我的理念是,如果您开始编写以 get 或 set 开头并采用零个或一个参数(分别)的方法名称,那么它就是属性的主要候选者。
回答by abatishchev
I prefer to use properties for add/set methods with 1parameter. If parameters are more, use methods.
我更喜欢使用带有1 个参数的添加/设置方法的属性。如果参数较多,则使用方法。
回答by Neil Bostrom
Properties should only be simple set and get one liners. Anything more and it should really be moved to a method. Complex code should always be in methods.
属性应该只设置简单并获得一个衬垫。任何更多,它应该真正转移到一个方法。复杂的代码应该总是在方法中。
回答by Robin Day
If you're setting an actual property of your object then you use a property.
如果您要设置对象的实际属性,则使用属性。
If you're performing a task / functionality then you use a method.
如果您正在执行任务/功能,那么您将使用一种方法。
In your example, it is a definite property being set.
在您的示例中,它是一个确定的属性。
If however, your functionality was to AppendToLabel then you would use a method.
但是,如果您的功能是 AppendToLabel,那么您将使用一种方法。
回答by Jeremy Edwards
Properties are really nice because they are accessible in the visual designer of visual studio, provided they have access.
属性非常好,因为它们可以在 Visual Studio 的视觉设计器中访问,前提是它们可以访问。
They use be used were you are merely setting and getting and perhaps some validation that does not access a significant amount of code. Be careful because creating complex objects during validation is not simple.
如果您只是在设置和获取某些验证,并且可能无法访问大量代码,则可以使用它们。要小心,因为在验证期间创建复杂对象并不简单。
Anything else methods are the preferred way.
任何其他方法都是首选方法。
It's not just about semantics. Using properties inappropriate start having weirdness occur in the visual studio visual designer.
这不仅仅是关于语义。使用不当的属性开始在 Visual Studio 视觉设计器中出现奇怪的现象。
For instance I was getting a configuration value within a property of a class. The configuration class actually opens a file and runs an sql query to get the value of that configuration. This caused problems in my application where the configuration file would get opened and locked by visual studio itself rather than my application because was not only reading but writing the configuration value (via the setter method). To fix this I just had to change it to a method.
例如,我在类的属性中获取配置值。配置类实际上打开一个文件并运行一个 sql 查询来获取该配置的值。这在我的应用程序中导致了问题,其中配置文件会被 Visual Studio 本身而不是我的应用程序打开和锁定,因为不仅读取而且写入配置值(通过 setter 方法)。为了解决这个问题,我只需要将其更改为一种方法。
回答by Marcus L
I only use properties for variable access, i.e. getting and setting individual variables, or getting and setting data in controls. As soon as any kind of data manipulation is needed/performed, I use methods.
我只使用属性来访问变量,即获取和设置单个变量,或获取和设置控件中的数据。一旦需要/执行任何类型的数据操作,我就会使用方法。
回答by Erik Funkenbusch
You need only look at the very name... "Property". What does it mean? The dictionary defines it in many ways, but in this case "an essential or distinctive attribute or quality of a thing" fits best.
你只需要看看名字……“财产”。这是什么意思?字典以多种方式定义它,但在这种情况下,“事物的基本或独特的属性或质量”最适合。
Think about the purpose of the action. Are you, in fact, altering or retrieving "an essential or distinctive attribute"? In your example, you are using a function to set a property of a textbox. That seems kind of silly, does it not?
想想行动的目的。事实上,您是否正在更改或检索“基本或独特的属性”?在您的示例中,您正在使用一个函数来设置文本框的属性。这看起来有点傻,不是吗?
Properties really are functions. They all compile down to getXXX() and setXXX(). It just hides them in syntactic sugar, but it's sugar that provides a semantic meaning to the process.
属性确实是函数。它们都编译为 getXXX() 和 setXXX()。它只是将它们隐藏在语法糖中,但是糖为过程提供了语义。
Think about properties like attributes. A car has many attributes. Color, MPG, Model, etc.. Not all properties are setable, some are calculatable.
想想属性之类的属性。一辆车有很多属性。颜色、MPG、型号等。并非所有属性都是可设置的,有些是可计算的。
Meanwhile, a Method is an action. GetColor should be a property. GetFile() should be a function. Another rule of thumb is, if it doesn't change the state of the object, then it should be a function. For example, CalculatePiToNthDigit(n) should be a function, because it's not actually changing the state of the Math object it's attached to.
同时,方法是一个动作。GetColor 应该是一个属性。GetFile() 应该是一个函数。另一个经验法则是,如果它不改变对象的状态,那么它应该是一个函数。例如,CalculatePiToNthDigit(n) 应该是一个函数,因为它实际上并没有改变它所附加的 Math 对象的状态。
This is maybe rambling a bit, but it really boils down to deciding what your objects are, and what they represent. If you can't figure out if it should be a property or function, maybe it doesn't matter which.
这可能有点啰嗦,但实际上归结为决定您的对象是什么,以及它们代表什么。如果你不知道它应该是一个属性还是一个函数,也许哪个都无关紧要。
回答by Muhammad Hasan Khan
Symantically properties are attributes of your objects. Methods are behaviors of your object.
符号属性是对象的属性。方法是对象的行为。
Label is an attribute and it makes more sense to make it a property.
标签是一个属性,让它成为一个属性更有意义。
In terms of Object Oriented Programming you should have a clear understanding of what is part of behavior and what is merely an attribute.
在面向对象编程方面,您应该清楚地了解什么是行为的一部分,什么只是一个属性。
Car { Color, Model, Brand }
汽车 { 颜色、型号、品牌 }
A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.
汽车具有颜色、型号和品牌属性,因此拥有 SetColor 或 SetModel 方法没有意义,因为我们不要求 Car 设置自己的颜色。
So if you map the property/method case to the real life object or look at it from symantic view point, your confusion will really go away.
因此,如果您将属性/方法案例映射到现实生活中的对象或从符号的角度来看它,您的困惑将真正消失。
回答by Chuck Conway
Properties are a way to inject or retrieve data from an object. They create an abstraction over variables or data within a class. They are analogous to getters and setters in Java.
属性是一种从对象注入或检索数据的方法。它们在类中创建了对变量或数据的抽象。它们类似于 Java 中的 getter 和 setter。
Methods encapsulate an operation.
方法封装了一个操作。
In general I use properties to expose single bits of data, or small calculations on a class, like sales tax. Which is derived from the number of items and their cost in a shopping cart.
通常,我使用属性来公开单个数据位,或对类进行小规模计算,例如销售税。这是根据购物车中的商品数量及其成本得出的。
I use methods when I create an operation, like retrieving data from the database. Any operation that has moving parts, is a candidate for a method.
我在创建操作时使用方法,例如从数据库中检索数据。任何具有活动部件的操作都是方法的候选者。
In your code example I would wrap it in a property if I need to access it outside it's containing class:
在您的代码示例中,如果我需要在它包含的类之外访问它,我会将它包装在一个属性中:
public Label Title
{
get{ return titleLabel;}
set{ titleLabel = value;}
}
Setting the text:
设置文本:
Title.Text = "Properties vs Methods";
If I was only setting the Text property of the Label this is how I would do it:
如果我只设置 Label 的 Text 属性,我会这样做:
public string Title
{
get{ return titleLabel.Text;}
set{ titleLabel.Text = value;}
}
Setting the text:
设置文本:
Title = "Properties vs Methods";