简体   繁体   English

方法调用公共/私有成员或方法最佳实践 - C#.NET

[英]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 有两个原因

  • Simplifies debugging; 简化调试; if you have an issue where a value is changed, or returns an unexpected value, you can set a breakpoint inside the property getter or setter and easily trap any access to the value. 如果您遇到更改值或返回意外值的问题,则可以在属性getter或setter中设置断点,并轻松捕获对该值的任何访问权限。
  • Reduces impact of changes, you can make changes to the field and it will affect very few places in the code directly. 减少更改的影响,您可以对字段进行更改,它将直接影响代码中的极少数位置。

Or, to put it in a single word: encapsulation . 或者,把它放在一个单词中: 封装

在某些情况下,您的公共属性可能包含您需要的一些逻辑,在这种情况下,如果您确定要使用私有成员变量,并且不将该功能公开给该公共属性,那么您将始终使用该属性而不是局部变量。外面的世界,使那个特定的方法私有化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM