c# - 堆叠使用语句与单独使用语句

标签 c# performance using-statement

在重构代码时,我偶然发现了一些堆叠的 using 语句(我说的是 10 到 15 条左右)。

using(X x=new X())
using(Y y=new Y())
using(Z z=new Z())
using(...)
{
    List<X> listX= x.GetParameterListByID(pID);
    List<Y> listY=y.GetParameterListByID(pID);
    ...
    ...
    //other (business) calls/code, like 20-30 lines, that don't need the using instances
}

类的例子是这样的

public class X : IDisposable{
  public List<XParameterInfo> GetParameterListByID(int? pID){
      const string query="SELECT name,value FROM parameters WHERE id=@ID";
      //query code here
      return queryResult;
  }
}

我首先想到的是,知道 using 基本上是 try{} finally{ x.Dispose(); },using 连接将保持打开/事件状态,直到 using block 中的代码完成,而它只需要填充一个列表。

以上是我的推测,如有错误请指正。 考虑到我说的是正确的,写一些像这样的东西会更好吗(性能,但主要是良好的实践)

List<X> listX;
List<Y> listY;
List<Z> listZ;
...
//for the example here I wrote out 3 but let's talk 10 or more

using(X x=new X())
{ 
   listX=x.GetParameterListByID(pID);
}
using(Y y=new Y())
{ 
   listY=y.GetParameterListByID(pID);
}
using(Z z=new Z())
{ 
   listZ=z.GetParameterListByID(pID);
} 
...
// other calls but now outside the using statements

或者它是否可以忽略不计,除了堆叠的 using 语句会带走嵌套代码的外观?

最佳答案

would it be better (performance wise)

这取决于使用中使用的类型。你不能做一个笼统的陈述。

性能不是唯一的因素,开放的资源会阻塞其他进程或导致内存问题。但另一方面,更紧凑的第一个版本增加了可读性。因此,您必须确定是否存在问题。如果没有,为什么要打扰?然后选择可读性和可维护性最好的代码。

但是你可以重构你的代码,使用一个方法来封装使用:

// in class X:
public static List<X> GetParameterListByID(int pID)
{
    using(X x = new X())
    { 
       return x.GetParameterListByID(pID);
    }
} 
// and same in other classes

现在代码没有用处了:

List<X> listX = X.GetParameterListByID(pID); // static method called
List<Y> listY = Y.GetParameterListByID(pID); // static method called

关于c# - 堆叠使用语句与单独使用语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093037/

相关文章:

c++ - 如果 new_size 不大于旧的,C++ 标准是否保证 std::string::resize(new_size) 不会导致分配?

c# - 是否存在使用不会处理对象的情况?

c# - 为什么不能在 C# 中没有大括号的 switch 部分中使用 using 变量?

java - 如何加速 Eclipse Juno?

c# - 关闭 SqlConnection 和 SqlCommand c#

c# - 如何在 C# 中向 IEnumerable 添加元素

c# - 如何在 EMGU 中使用精确的 Opencv C++ 函数?

c# - 从 ActionExecutingContext 获取原始端口?

c# - 什么是界面鸭子类型?

python - PySerial 从 Arduino 读取时速度变慢