方法调用公共/私有成员或方法最佳实践 - C#.NET
从私有方法和公共方法调用成员/字段的最佳实践是什么?私有方法应该始终调用私有字段还是应该调用公共成员?
private string _name;
public string Name
{
get {return _name; }
set { _name = value; }
}
public void DoSomething()
{
_doSomething();
}
private void _doSomething()
{
_name.ToLower();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更喜欢让所有代码都通过公共接口,只是为了减少代码中访问实际支持字段的位置数量。有两个原因:
或者,用一个词来形容:封装。
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.
在某些情况下,您的公共属性可能包含您需要的一些逻辑,在这种情况下,如果您确定要使用私有成员变量,并且不将该功能公开给私有成员变量,那么您将始终使用该属性而不是局部变量。外部世界,将该特定方法设为私有。
In some cases your public property might contain some logic which you need and in that case you will always use the property instead of the local variable, if you are sure that you want to use the private member variable, and not expose that functionality to the outside world, make that particular method private.