[英]Method Calling Public/Private Members or Methods Best Practice - C#.NET
What is the best practice for calling members/fields from a private method and public method? 从私有方法和公共方法调用成员/字段的最佳做法是什么? Should the private method always call private fields or should they call the public members?
私有方法应该总是调用私有字段还是应该调用公共成员?
private string _name;
public string Name
{
get {return _name; }
set { _name = value; }
}
public void DoSomething()
{
_doSomething();
}
private void _doSomething()
{
_name.ToLower();
}
I prefer to have all code go through the public interface, simply to reduce the number of places in the code that accesses the actual backing field. 我更喜欢让所有代码都通过公共接口,只是为了减少访问实际支持字段的代码中的位数。 Two reasons are
有两个原因
Or, to put it in a single word: encapsulation . 或者,把它放在一个单词中: 封装 。
在某些情况下,您的公共属性可能包含您需要的一些逻辑,在这种情况下,如果您确定要使用私有成员变量,并且不将该功能公开给该公共属性,那么您将始终使用该属性而不是局部变量。外面的世界,使那个特定的方法私有化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.