为什么要在属性访问器中使用私有变量? [英] Why should I use a private variable in a property accessor?
问题描述
对不起,如果我是菜鸟,我有这个疑问,为什么我们使用私有变量并使用属性设置它们?
Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?
为什么我们不能单独使用属性?
Why can't we just use properites alone ?
我说的是这样的情况
private string _testVariable;
public string MyProperty
{
get { return _testVariable;}
set {_testVariable = value;}
}
我正在考虑简单地使用
public string MyProperty { get; set; }
为什么会有多余的私有变量?这两种策略有什么不同吗?任何人都可以对此有所了解.
Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.
谢谢
推荐答案
您的示例在语义上是相同的.简洁的属性声明语法(只有 { get; set; }
)是 C# 3.0 中可用的快捷方式.编译器实际上创建了一个私有的支持变量和一个简单的 getter 和 setter,就像你的第一个例子一样.
Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }
) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.
如果您所做的只是创建一个 getter 和 setter(并且当任何一个发生时实际上什么都没有发生),那么简洁的语法是一个不错的选择.如果您在设置值时必须执行任何其他操作(例如重绘控件),则需要完整的语法.
If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.
这篇关于为什么要在属性访问器中使用私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!