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

发布于 2024-09-03 04:39:01 字数 284 浏览 4 评论 0原文

从私有方法和公共方法调用成员/字段的最佳实践是什么?私有方法应该始终调用私有字段还是应该调用公共成员?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁吢 2024-09-10 04:39:01

我更喜欢让所有代码都通过公共接口,只是为了减少代码中访问实际支持字段的位置数量。有两个原因:

  • 简化调试;如果您遇到值更改或返回意外值的问题,您可以在属性 getter 或 setter 内设置断点,并轻松捕获对该值的任何访问。
  • 减少更改的影响,您可以对字段进行更改,并且它会直接影响代码中的极少数地方。

或者,用一个词来形容:封装

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.
  • 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.

冷…雨湿花 2024-09-10 04:39:01

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文