在 C# 中寻找一个简短的 getter/setter 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11159438/
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
Looking for a short & simple example of getters/setters in C#
提问by CM90
I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, but not so much in C# (as far as I can tell). I have read books and articles already, so my question is, to those of you who understand getters & setters in C#, what example would you personally use if you were teaching the concept to a complete beginner (this would include as few lines of code as possible)?
我无法理解C# 语言中 getter 和 setter 的概念。在像 Objective-C 这样的语言中,它们似乎是系统不可或缺的一部分,但在 C# 中则不然(据我所知)。我已经阅读过书籍和文章,所以我的问题是,对于那些了解 C# 中的 getter 和 setter 的人,如果您将这个概念教给一个完整的初学者,您个人会使用什么示例(这将包括几行代码尽可能)?
回答by Jon Senchyna
In C#, Propertiesrepresent your Getters and Setters.
在 C# 中,属性代表您的 Getter 和 Setter。
Here's an example:
下面是一个例子:
public class PropertyExample
{
private int myIntField = 0;
public int MyInt
{
// This is your getter.
// it uses the accessibility of the property (public)
get
{
return myIntField;
}
// this is your setter
// Note: you can specify different accessibility
// for your getter and setter.
protected set
{
// You can put logic into your getters and setters
// since they actually map to functions behind the scenes
DoSomeValidation(value)
{
// The input of the setter is always called "value"
// and is of the same type as your property definition
myIntField = value;
}
}
}
}
You would access this property just like a field. For example:
您可以像访问字段一样访问此属性。例如:
PropertyExample example = new PropertyExample();
example.MyInt = 4; // sets myIntField to 4
Console.WriteLine( example.MyInt ); // prints 4
A few other things to note:
其他一些注意事项:
- You don't have to specifiy both a getter and a setter, you can omit either one.
- Properties are just "syntactic sugar" for your traditional getter and setter. The compiler will actually build get_ and set_ functions behind the scenes (in the compiled IL) and map all references to your property to those functions.
- 您不必同时指定 getter 和 setter,您可以省略任何一个。
- 属性只是传统 getter 和 setter 的“语法糖”。编译器实际上会在幕后(在已编译的 IL 中)构建 get_ 和 set_ 函数,并将对您的属性的所有引用映射到这些函数。
回答by Ikspeto
Most languages do it this way, and you can do it in C# too.
大多数语言都是这样做的,您也可以在 C# 中这样做。
public void setRAM(int RAM)
{
this.RAM = RAM;
}
public int getRAM()
{
return this.RAM;
}
But C# also gives a more elegant solution to this :
但是 C# 也为此提供了一个更优雅的解决方案:
public class Computer
{
int ram;
public int RAM
{
get
{
return ram;
}
set
{
ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
}
}
}
And later access it with.
稍后访问它。
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;
For newer versions of C# it's even better :
对于较新版本的 C#,它甚至更好:
public class Computer
{
public int RAM { get; set; }
}
and later :
然后 :
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;
回答by SliverNinja - MSFT
This would be a get/set in C# using the smallest amount of code possible. You get auto-implemented properties in C# 3.0+.
这将是使用尽可能少的代码在 C# 中的获取/设置。您可以在 C# 3.0+ 中获得自动实现的属性。
public class Contact
{
public string Name { get; set; }
}
回答by KF2
Simple example
简单的例子
public class Simple
{
public int Propery { get; set; }
}
回答by Zingam
As far as I understand getters and setters are to improve encapsulation. There is nothing complex about them in C#.
据我了解 getter 和 setter 是为了改进封装。在 C# 中,它们并不复杂。
You define a property of on object like this:
您可以像这样定义 on 对象的属性:
int m_colorValue = 0;
public int Color
{
set { m_colorValue = value; }
get { return m_colorValue; }
}
This is the most simple use. It basically sets an internal variable or retrieves its value. You use a Property like this:
这是最简单的用法。它基本上设置一个内部变量或检索其值。你使用这样的属性:
someObject.Color = 222; // sets a color 222
int color = someObject.Color // gets the color of the object
You could eventually do some processing on the value in the setters or getters like this:
您最终可以对 setter 或 getter 中的值进行一些处理,如下所示:
public int Color
{
set { m_colorValue = value + 5; }
get { return m_colorValue - 30; }
}
if you skip set or get, your property will be read or write only. That's how I understand the stuff.
如果你跳过 set 或 get,你的属性将是只读的或只写的。这就是我对这些东西的理解。
回答by Kevin DiTraglia
C# introduces properties which do most of the heavy lifting for you...
C# 引入了为您完成大部分繁重工作的属性......
ie
IE
public string Name { get; set; }
is a C# shortcut to writing...
是 C# 编写的快捷方式...
private string _name;
public string getName { return _name; }
public void setName(string value) { _name = value; }
Basically getters and setters are just means of helping encapsulation. When you make a class you have several class variables that perhaps you want to expose to other classes to allow them to get a glimpse of some of the data you store. While just making the variables public to begin with may seem like an acceptable alternative, in the long run you will regret letting other classes manipulate your classes member variables directly. If you force them to do it through a setter, you can add logic to ensure no strange values ever occur, and you can always change that logic in the future without effecting things already manipulating this class.
基本上 getter 和 setter 只是帮助封装的手段。当您创建一个类时,您可能希望将多个类变量公开给其他类,以允许他们瞥见您存储的一些数据。虽然一开始就公开变量似乎是一个可以接受的选择,但从长远来看,您会后悔让其他类直接操作您的类成员变量。如果您通过 setter 强制他们执行此操作,则可以添加逻辑以确保不会出现奇怪的值,并且您可以在将来随时更改该逻辑,而不会影响已经在操纵此类的事情。
ie
IE
private string _name;
public string getName { return _name; }
public void setName(string value)
{
//Don't want things setting my Name to null
if (value == null)
{
throw new InvalidInputException();
}
_name = value;
}
回答by Kevin Aenmey
Internally, getters and setters are just methods. When C# compiles, it generates methods for your getters and setters like this, for example:
在内部,getter 和 setter 只是方法。当 C# 编译时,它会像这样为你的 getter 和 setter 生成方法,例如:
public int get_MyProperty() { ... }
public void set_MyProperty(int value) { ... }
C# allows you to declare these methods using a short-hand syntax. The line below will be compiled into the methods above when you build your application.
C# 允许您使用简写语法声明这些方法。当您构建应用程序时,下面的行将被编译为上面的方法。
public int MyProperty { get; set; }
or
或者
private int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; } // value is an implicit parameter containing the value being assigned to the property.
}
回答by spots
Getters and Setters in C# are something that simplifies the code.
C# 中的 Getter 和 Setter 可以简化代码。
private string name = "spots";
public string Name
{
get { return name; }
set { name = value; }
}
And calling it (assume we have a person obj with a name property):
并调用它(假设我们有一个带有 name 属性的 person obj):
Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"
This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:
这简化了您的代码。在 Java 中,您可能必须有两种方法,一种是 Get(),一种是 Set() 属性,而在 C# 中,这一切都在一个地方完成。我通常在课程开始时这样做:
public string foobar {get; set;}
This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!
这为我的 foobar 属性创建了一个 getter 和 setter。调用它的方式与之前显示的相同。需要注意的是,您不必同时包含 get 和 set。如果您不想修改属性,请不要包含 set!
回答by bleepzter
I think a bit of code will help illustrate what setters and getters are:
我认为一些代码将有助于说明什么是 setter 和 getter:
public class Foo
{
private string bar;
public string GetBar()
{
return bar;
}
public void SetBar(string value)
{
bar = value;
}
}
In this example we have a private member of the class that is called bar. The GetBar and SetBar methods do exactly what they are named - one retrieves the bar member, and the other sets its value.
在这个例子中,我们有一个名为 bar 的类的私有成员。GetBar 和 SetBar 方法完全按照它们的名字来做——一个检索 bar 成员,另一个设置它的值。
In c# 1.1 + you have properties. The basic functionality is also the same:
在 c# 1.1 + 你有属性。基本功能也是一样的:
public class Foo
{
private string bar;
public string Bar
{
get { return bar; }
set { bar = value; }
}
}
The private member bar is not accessible outside the class. However the public "Bar" is, and it has two accessors - get, which just as the example above "GetBar()" returns the private member, and also a set - which corresponds to the SetBar(string value) method in the forementioned example.
私人成员栏在课堂外无法访问。然而,公共“Bar”是,它有两个访问器——get,就像上面的例子“GetBar()”返回私有成员,还有一个集合——它对应于前面提到的 SetBar(string value) 方法例子。
Starting with C# 3.0 and above the compiler became optimized to the point where such properties do not need to have the private member as their source. The compiler automatically generates a private member of that type and uses it as a source of a property.
从 C# 3.0 及更高版本开始,编译器已优化到此类属性不需要将私有成员作为其源的程度。编译器会自动生成该类型的私有成员并将其用作属性的源。
public class Foo
{
public string Bar { get; set; }
}
what the code shows is an automatic property that has a private member generated by the compiler. You don't see the private member but it is there. This also introduced a couple of other issues - mainly with access control. In C# 1.1, and 2.0 you could omit the get or set portion of a property:
代码显示的是一个自动属性,它具有由编译器生成的私有成员。您看不到私有成员,但它在那里。这还引入了其他一些问题——主要是访问控制。在 C# 1.1 和 2.0 中,您可以省略属性的 get 或 set 部分:
public class Foo
{
private string bar;
public string Bar
{
get{ return bar; }
}
}
Giving you the chance to restrict how other objects interact with the "Bar" property of the Foo class. Starting with C# 3.0 and above - if you chose to use automatic properties you would have to specify the access to the property as follows:
让您有机会限制其他对象如何与 Foo 类的“Bar”属性交互。从 C# 3.0 及更高版本开始 - 如果您选择使用自动属性,则必须按如下方式指定对属性的访问:
public class Foo
{
public string Bar { get; private set; }
}
What that means is that only the class itself can set Bar to some value, however anyone could read the value in Bar.
这意味着只有类本身可以将 Bar 设置为某个值,但是任何人都可以读取 Bar 中的值。
回答by Vlad
My explanation would be following. (It's not so short, but it's quite simple.)
我的解释如下。(它不是那么短,但它很简单。)
Imagine a class with a variable:
想象一个带有变量的类:
class Something
{
int weight;
// and other methods, of course, not shown here
}
Well, there is a small problem with this class: no one can see the weight. We could make weightpublic, but then everyonewould be able to change the weightat any moment (which is perhaps not what we want). So, well, we can do a function:
嗯,这个类有一个小问题:没有人可以看到weight. 我们可以weight公开,但每个人都可以随时更改weight(这可能不是我们想要的)。所以,好吧,我们可以做一个函数:
class Something
{
int weight;
public int GetWeight() { return weight; }
// and other methods
}
This is already better, but now everyone instead of plain something.Weighthas to type something.GetWeight(), which is, well, ugly.
这已经更好了,但现在每个人都something.Weight必须输入而不是普通的something.GetWeight(),这很丑陋。
With properties, we can do the same, but the code stays clean:
使用属性,我们可以做同样的事情,但代码保持干净:
class Something
{
public int weight { get; private set; }
// and other methods
}
int w = something.weight // works!
something.weight = x; // doesn't even compile
Nice, so with the properties we have finer control over the variable access.
很好,所以有了属性,我们可以更好地控制变量访问。
Another problem: okay, we want the outer code to be able to set weight, but we'd like to control its value, and not allow the weights lower than 100. Moreover, there are is some other inner variable density, which depends on weight, so we'd want to recalculate the densityas soon as the weightchanges.
另一个问题:好的,我们希望外部代码能够设置weight,但我们想控制它的值,并且不允许低于100的权重。此外,还有一些其他的内部变量density,这取决于weight,所以我们希望density在weight发生变化后立即重新计算。
This is traditionally achieved in the following way:
传统上,这是通过以下方式实现的:
class Something
{
int weight;
public int SetWeight(int w)
{
if (w < 100)
throw new ArgumentException("weight too small");
weight = w;
RecalculateDensity();
}
// and other methods
}
something.SetWeight(anotherSomething.GetWeight() + 1);
But again, we don't want expose to our clients that setting the weight is a complicated operation, it's semantically nothing but assigning a new weight. So the code with a setter looks the same way, but nicer:
但同样,我们不想让我们的客户知道设置权重是一个复杂的操作,它在语义上只是分配一个新的权重。所以带有 setter 的代码看起来相同,但更好:
class Something
{
private int _w;
public int Weight
{
get { return _w; }
set
{
if (value < 100)
throw new ArgumentException("weight too small");
_w = value;
RecalculateDensity();
}
}
// and other methods
}
something.Weight = otherSomething.Weight + 1; // much cleaner, right?
So, no doubt, properties are "just" a syntactic sugar. But it makes the client's code be better. Interestingly, the need for property-like things arises very often, you can check how often you find the functions like GetXXX() and SetXXX() in the other languages.
因此,毫无疑问,属性“只是”一种语法糖。但它使客户端的代码更好。有趣的是,对类似属性的东西的需求经常出现,你可以检查你在其他语言中找到像 GetXXX() 和 SetXXX() 这样的函数的频率。

