C#中“get”和“set”属性的目的是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10827337/
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
What is the purpose of the "get" and "set" properties in C#
提问by TechGuy
I saw some get set method to set values. Can anyone tell me the purpose of this?
我看到了一些 get set 方法来设置值。谁能告诉我这样做的目的是什么?
public string HTTP_USER_NAME
{
get
{
return UserName;
}
set
{
UserName = value;
}
}
public string HTTP_USER_PASSWORD
{
get
{
return UserPwd;
}
set
{
UserPwd = value;
}
}
Actually why use these things. For global access, or is there some other reason for this type of thing?
其实为什么要用这些东西。对于全局访问,或者这种类型的事情还有其他原因吗?
采纳答案by Jupaol
They are just accessors and mutators. That's how properties are implemented in C#
它们只是访问器和修改器。这就是属性在 C# 中的实现方式
In C# 3 you can use auto-implemented properties like this:
在 C# 3 中,您可以使用自动实现的属性,如下所示:
public int MyProperty { get; set; }
This code is automatically translated by the compiler to code similar to the one you posted, with this code is easier to declare properties and they are ideal if you don't want to implement custom logic inside the setor getmethods, you can even use a different accessor for the setmethod making the property immutable
这段代码由编译器自动翻译成类似于你发布的代码,这段代码更容易声明属性,如果你不想在setorget方法中实现自定义逻辑,它们是理想的,你甚至可以使用不同的set使属性不可变的方法的访问器
public int MyProperty { get; private set; }
In the previous sample the MyPropertywill be read only outside the class where it was declared, the only way to mutate it is by exposing a method to do it or just through the constructor of the class. This is useful when you want to control and make explicit the state change of your entity
在前面的示例中,MyProperty将仅在声明它的类之外读取,改变它的唯一方法是公开一个方法来执行它或仅通过类的构造函数。当您想要控制和明确实体的状态更改时,这很有用
When you want to add some logic to the properties then you need to write the properties manually implementing the getand setmethods just like you posted:
当您想向属性添加一些逻辑时,您需要手动编写属性来实现get和set方法,就像您发布的一样:
Example implementing custom logic
实现自定义逻辑的示例
private int myProperty;
public int MyProperty
{
get
{
return this.myProperty;
}
set
{
if(this.myProperty <=5)
throw new ArgumentOutOfRangeException("bad user");
this.myProperty = value;
}
}
回答by kaveman
Standard way to implement properties in C#. UserNameand UserPwdare private member variables (stringtype) of the class where these 2 methods are defined.
在 C# 中实现属性的标准方法。UserName并且是定义这两个方法的类的UserPwd私有成员变量(string类型)。
回答by Shyju
HTTP_USER_NAMEand HTTP_USER_PASSWORDare the public properties of your class. UserNameand UserPwdcould be your private field. And you are allowing other people to set or get the values via these public properties. No direct accesss to private propeties. Also you can do some logic inside the get method of the property.Ex : you will have a public property called Ageand in the get method of that, you may read the value of your private field called "dateOfBirth" and do some calculation ( CurrentYear-dateOfBirth) and return that as the Age.
HTTP_USER_NAME并且HTTP_USER_PASSWORD是您班级的公共属性。UserName并且UserPwd可能是您的私人领域。并且您允许其他人通过这些公共属性设置或获取值。不能直接访问私有财产。您也可以在属性的 get 方法中执行一些逻辑。例如:您将调用一个公共属性Age,在该属性的 get 方法中,您可以读取名为“ dateOfBirth”的私有字段的值并进行一些计算(CurrentYear- dateOfBirth)并将其作为年龄返回。
回答by Tilak
Properties are just accessors over fields. They allow to do certain operations (if needed), and provide controlled access to fields.
属性只是字段的访问器。它们允许执行某些操作(如果需要),并提供对字段的受控访问。
If you want to know when to use Properties, and when to use Only fields, Check the link Properties vs Fields – Why Does it Matter? (Jonathan Aneja)
如果您想知道何时使用属性,何时使用仅字段,请查看链接属性与字段 - 为什么重要?(乔纳森·阿内贾)
回答by stay_hungry
Check these links,.. they gives clear explanation.
检查这些链接,.. 他们给出了明确的解释。
http://www.dotnetperls.com/property
http://www.dotnetperls.com/property
http://code.anjanesh.net/2008/02/property-getters-setters.html
http://code.anjanesh.net/2008/02/property-getters-setters.html
if UserName and UserPwd are class variables, better to use like this
如果 UserName 和 UserPwd 是类变量,最好这样使用
_userName
_userPwd
回答by rob_williams
It seems as though you understand the functionality of getters and setters, and others answered that question. "Normal" class variables (without getters and setters) are called "fields", and "properties" (which have the getters and setters) encapsulate fields.
似乎您了解 getter 和 setter 的功能,其他人回答了这个问题。“普通”类变量(没有 getter 和 setter)被称为“字段”,而“属性”(有 getter 和 setter)封装了字段。
The purposeof properties is to control outside access to fields. If you want a variable to be read-only to outside logic, you can omit the setters, like so:
属性的目的是控制外部对字段的访问。如果您希望变量对外部逻辑只读,则可以省略设置器,如下所示:
private int dataID;
public int DataID {
get { return dataID; }
}
You can also make the setter private and achieve the same read-only functionality.
您还可以将 setter 设为私有并实现相同的只读功能。
If an object has a chance of being null (for whatever reason), you can guarantee an instance always exists like this:
如果一个对象有可能为空(无论出于何种原因),您可以保证一个实例始终存在,如下所示:
private Object instance;
public Object Instance {
get {
if (instance == null)
instance = new Object();
return instance;
}
}
Another use for properties is defining indexers.
属性的另一个用途是定义索引器。
//in class named DataSet
private List<int> members;
public int this[int index] {
get { return members[index]; }
}
With that indexer defined, you can access an instance of DataSet like this:
定义该索引器后,您可以像这样访问 DataSet 的实例:
int member = dataSet[3];
回答by Jodrell
From Properties (C# Programming Guide)
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
属性是一个成员,它提供了一种灵活的机制来读取、写入或计算私有字段的值。属性可以像公共数据成员一样使用,但它们实际上是称为访问器的特殊方法。这使数据可以轻松访问,并且仍然有助于提高方法的安全性和灵活性。
In this example, the TimePeriodclass stores a time period. Internally the class stores the time in seconds, but a property named Hoursenables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.
在此示例中,TimePeriod该类存储一个时间段。该类在内部以秒为单位存储时间,但名为的属性Hours使客户端能够以小时为单位指定时间。小时属性的访问器执行小时和秒之间的转换。
Example
例子
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
Properties Overview
属性概述
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
A getproperty accessor is used to return the property value, and a setaccessor is used to assign a new value. These accessors can have different access levels. For more information, see Restricting Accessor Accessibility (C# Programming Guide).
The valuekeyword is used to define the value being assigned by the setaccessor.
Properties that do not implement a setaccessor are read only.
For simple properties that require no custom accessor code, consider the option of using auto-implemented properties. For more information, see Auto-Implemented Properties (C# Programming Guide).
属性使类能够公开获取和设置值的公共方式,同时隐藏实现或验证代码。
一个GET属性访问器用于返回属性值,并且设置访问用于指定一个新值。这些访问者可以有不同的访问级别。有关更多信息,请参阅限制访问器可访问性(C# 编程指南)。
的值关键字用于限定值由被分配集访问器。
未实现set访问器的属性是只读的。
对于不需要自定义访问器代码的简单属性,请考虑使用自动实现的属性的选项。有关更多信息,请参阅自动实现的属性(C# 编程指南)。

