在重构代码时,我偶然发现了一些堆叠的 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/