方法调用公共/私有成员或方法的最佳实践 - C#.NET [英] Method Calling Public/Private Members or Methods Best Practice - C#.NET

查看:333
本文介绍了方法调用公共/私有成员或方法的最佳实践 - C#.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是从一个私有方法和公有方法调用成员/领域的最佳实践?如果私有方法始终调用私有字段或者应该叫公共成员?

 私人字符串_name;
公共字符串名称
{
   {返回_name; }
   集合{_name =价值; }
}

公共无效DoSomething的()
{
   _做一点事();
}


私人无效_doSomething()
{
   _name.ToLower();
}
 

解决方案

我preFER让所有code通过公共接口,简单地减少code访问的名额实际的支持字段。两个原因

  • 简化调试;如果你有一个值的改变,或返回一个意外值的问题,您可以设置属性的getter和setter方法​​,轻松地捕获任何访问值内的断点。
  • 在减少变化的影响,您可以更改到外地,这将影响到$ C $直接ç极少数地方。

或者,把它放在一个字:封装

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

这篇关于方法调用公共/私有成员或方法的最佳实践 - C#.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆