简体   繁体   中英

What is difference between this two C# methods

What is the difference between these two cases. Firstly, if I open the connection and pass it into my method as a parameter, compared to opening the connection directly in the method?

cnn.open()
func(cnn,param1,param2);

vs

func(cnn, param1,param2)
{
  cnn.open();
  //open connection here
}

与您发布的代码没有什么不同,除了在一种情况下,您的调用函数需要注意打开/关闭连接,在另一种情况下,您希望函数可以完成此操作。

The difference is that in the second method, you open the connection.

In the first method you expect the method to only use a connection not caring about cleaning up the resources.

没有功能上的区别,但用于打开和关闭连接的线通常应尽可能靠近,因此它们应采用相同的方法。

The difference is in how you want to use the connection and performance. If the function is a once off call and you are calling no other functions, or not doing anything else with the connection, then the second version of the function could even be reduced to:

func(param1, param2) {
    Connection c = ....
    c.Open(...);
    ...
    c.Close();
}

However if you are calling many functions on the connection, even calling the function many times on the connection or if the creation and configuration of the connection is at a higher layer in your code, then you should use the first version of the function, with the addition of throwing an exception if the connection is not opened.

Well, I think you shouldn't ask for the different rather you should explain the situation you are in and ask for recommendation for what case must be used.

Anyway, As Everybody told you In case 2 the connection object and its life cycle is encapsulated within the callee function. This is recommended if database operation out side this function is not desired.

Otherwise if you have any other database activity to be done out side this function scope like in caller function or any other function(other than func) being called from caller function then you should use the Case 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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