简体   繁体   English

允许将私有变量放在C#的公共方法中吗?

[英]It is allowed to put private variables inside public methods in C#?

I have a little code 我有一些代码

public void StartConnection(){
  _connection = new DatabaseConnection();
}

public Results ExecuteQuery( string format ){
  _queryExecuter.SetText = string.Format(_queryString, format);

  return _queryExecuter.Execute();
}

What I did, it allowed to use private members inside public methods ? 我做了什么,它允许在公共方法中使用私有成员?

I mention that public methods will be used in another classes (from different project but in same solution). 我提到公共方法将在另一个类中使用(来自不同的项目,但在相同的解决方案中)。

Or I have to create private methods and use inside the private variables ? 还是我必须创建私有方法并在私有变量中使用?

I need just advices. 我只需要建议。

Thank you 谢谢

Yes its a very fundamental programming philosophy called encapsulation . 是的,它是一种非常基本的编程哲学,称为封装 Its perfectly valid and encouraged to do so. 它是完全有效的,并鼓励这样做。 In your case, only you know how to use your connection object and "restrict" how to use it via your public method, thus keeping your application in your defined bounds. 就您而言,只有您知道如何使用连接对象,并通过公共方法“限制”如何使用它,从而使您的应用程序处于定义的范围内。

What I did, it allowed to use private members inside public methods ? 我做了什么,它允许在公共方法中使用私有成员?

Yes, you can absolutely use private members within public ones. 是的,您绝对可以在公共成员中使用私有成员。 They'd be pretty useless otherwise! 否则它们将毫无用处! (If you could only use private members within other private members, how could you ever use any of them?) (如果您只能在其他私人成员中使用私人成员,您将如何使用其中任何一个?)

A lot of the point of encapsulation is to hide the implementation details (the private members) from the public API. 封装的许多要点是从公共API隐藏实现细节 (私有成员)。

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

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