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 .
在某些情况下,您的公共属性可能包含您需要的一些逻辑,在这种情况下,如果您确定要使用私有成员变量,并且不将该功能公开给该公共属性,那么您将始终使用该属性而不是局部变量。外面的世界,使那个特定的方法私有化。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.