简体   繁体   English

这两种C#方法之间有什么区别

[英]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. 无论如何,正如每个人都告诉您的那样,在第2种情况下,连接对象及其生命周期封装在被调用方函数中。 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. 否则,如果您要在此函数范围之外完成任何其他数据库活动,例如在调用者函数中或从调用者函数中调用的任何其他函数(func除外),则应使用情况1。

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

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