get:set的目的是什么? [英] What is the purpose of get : set?
问题描述
C#中的许多代码示例包含 get
和 set
代码块.他们的目的是什么?我复制这些块,使其出现在示例代码中,但不知道其用途.有人可以向我解释一下吗?
Many code samples in C# contain get
and set
code blocks. What is the purpose of them? I copy these blocks whey they appear in sample code, but have no idea what it is used for. Can someone please explain this to me?
推荐答案
通过字母和数字设置器,可以将一对函数组合为一个属性,并允许您使用看起来像成员访问表达式或适当赋值的语法看起来像显式函数调用的语法.
Getters and setters enable you to combine a pair of functions into one property, and let you use a syntax that looks like a member access expression or an assignment in place of syntax that looks like an explicit function call.
这是一个小例子:代替这个
Here is a small example: instead of this
class Example {
private int x;
public int GetX() {return x;}
public void SetX(int value) { x = value;}
}
Example e = new Example();
e.SetX(123);
Console.WriteLine("X = {0}", e.GetX());
他们让您这样做:
class Example {
public int X {get;set;}
}
Example e = new Example();
e.X = 123;
Console.WriteLine("X = {0}", e.X);
第二个代码段的语法更易于阅读,因为 X
看起来像一个变量.同时,第二个片段提供相同级别的 封装 ,让您将实现隐藏在属性的后面.
The syntax of the second code snippet is easier to read, because X
looks like a variable. At the same time, the second snippet provides the same level of encapsulation, letting you hide the implementation behind the property.
这篇关于get:set的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!