当使用get;组;在c# [英] When to use get; set; in c#
问题描述
我没有理解上的差异是什么初始化变量,获取其值是这样的:
I'm failing to understand what the difference is between initializing a variable, getting its value like this:
//define a local variable.
int i;
i= 0;
Console.WriteLine(i);
和获取;组;用法:
and the get; set; usage:
public int i
{
get;
set;
}
i = 0;
Console.WriteLine(i);
我读过一些文章,但不明白的时候我都会使用它。
I've read some articles, but don't understand when I would use it.
推荐答案
基本上,在这种情况下,没有区别的使用属性的(多)的优点,被添加的能力<强>活动,以你的财产,像这样:
Basically, in that case, there is no difference, of the (many) advantages of using a property is the ability to add Events to your property, like so:
public delegate void ChangedEventHandler(object sender, EventArgs e);
int m_i = 0;
public int i
{
get { return m_i; }
set { m_i = value; iChanged(self, null); }
}
public ChangedEventHandler iChanged;
这允许代码知道什么时候我已经改变(可能有一些语法错误,我的天堂T专注于C#在一段时间,但这个想法是相似的)。这是的WinForms非常重要的,因为这是了解一个按钮(或类似)已被点击时的主要方式。
This allows for code to know when I has been changed (there might be some syntax errors, I haven't focused on C# in a while, but the idea is similar). This is extremely important in winforms, as this is the major way of knowing when a button (or similar) has been clicked.
此外,这允许附加功能中的属性,如:的设定部检查它是否在一定范围内,像这样的:
Also, this allows for additional functionality in the setter of a property, e.g. checking if it is in a certain range, like this:
int m_i = 0;
public int i {
get { return m_i; }
set { if (value > 10) throw new Exception("I cannot be greater than 10!"); m_i = value; }
}
这篇关于当使用get;组;在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!