访问您自己的类中的成员:使用(自动)属性?
我已经将这个问题创建为社区wiki,因为没有正确或错误的答案。我只想知道社群对这个具体问题的看法。
I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.
当你有一个包含实例变量的类,并且你创建的属性只是getter和setter对于这些实例变量,你应该使用你自己的类中的属性,还是应该总是使用实例变量?
When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?
在C#3.0中有自动属性更难的决定。
Having auto-properties in C# 3.0 made this an even harder decision.
使用属性:
public class MyClass
{
private string _name;
// could be an auto-property of-course
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = Name;
// ...
Name = "someValue";
// ...
}
}
变量:
public class MyClass
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = _name;
// ...
_name = "someValue";
// ...
}
}
>
个人而言,我总是使用后者(实例变量),因为我觉得属性只应该其他类使用,而不是您自己。这就是为什么我大部分远离自动属性以及。
Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.
当然,当属性setter(或getter)做一点不仅仅是包装实例
Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.
这是一个相当常见的问题。这里是我的文章,描述一些问题:
This is a fairly frequently asked question. Here's my article that describes some of the issues:
http://blogs.msdn.com/ericlippert/archive/2009/01/14/automatic-vs-explicit-properties.aspx