将代码重构为 using 语句
我有一个包含很多方法的 dal 层,所有方法都调用存储过程,一些返回列表(因此使用 SqlDataReader
),其他则仅调用特定值。
我有一个创建 SqlCommand
的辅助方法:
protected SqlCommand CreateSprocCommand(string name, bool includeReturn, SqlDbType returnType)
{
SqlConnection con = new SqlConnection(this.ConnectionString);
SqlCommand com = new SqlCommand(name, con);
com.CommandType = System.Data.CommandType.StoredProcedure;
if (includeReturn)
com.Parameters.Add("ReturnValue", returnType).Direction = ParameterDirection.ReturnValue;
return com;
}
现在我的平均(过度简化)方法主体如下所示:
SqlCommand cmd = CreateSprocCommand("SomeSprocName"); //an override of the above mentioned method
try {
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
//some code looping over the recors
}
//some more code to return whatever needs to be returned
}
finally {
cmd.Connection.Dispose();
}
有没有办法重构它,这样我就不会丢失我的辅助函数(它确实相当多的重复性工作),但还能使用 using
吗?
I have a dal layer with lots of methods, all of them call stored procedures, some return lists (so with a use of SqlDataReader
), others only a specific value.
I have a helper method that creates the SqlCommand
:
protected SqlCommand CreateSprocCommand(string name, bool includeReturn, SqlDbType returnType)
{
SqlConnection con = new SqlConnection(this.ConnectionString);
SqlCommand com = new SqlCommand(name, con);
com.CommandType = System.Data.CommandType.StoredProcedure;
if (includeReturn)
com.Parameters.Add("ReturnValue", returnType).Direction = ParameterDirection.ReturnValue;
return com;
}
Now my average (overly simplified) method body look like:
SqlCommand cmd = CreateSprocCommand("SomeSprocName"); //an override of the above mentioned method
try {
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
//some code looping over the recors
}
//some more code to return whatever needs to be returned
}
finally {
cmd.Connection.Dispose();
}
Is there a way to refactor this, so that I won't lose my helper function (it does quite a bit of otherwise repetitive work), and yet be able to use using
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种方法是将其从返回命令更改为接受使用该命令的委托:(
请注意,我还删除了
includeReturn
参数并使returnType
可为空。只需传递null
表示“无返回值”。)您可以将其与 lambda 表达式(或匿名方法)一起使用:
这样处置与创建位于同一位置,调用者无需担心它。 我非常喜欢这种模式 - 现在我们有了 lambda 表达式,它变得更加简洁。
One way is to change it from returning a command to taking a delegate which uses the command:
(Note that I've also removed the
includeReturn
parameter and madereturnType
nullable instead. Just passnull
for "no return value".)You'd use this with a lambda expression (or anonymous method):
That way the disposal is in the same place as the creation, and the caller just doesn't need to worry about it. I'm becoming quite a fan of this pattern - it's a lot cleaner now that we've got lambda expressions.
你可以这样做:
并这样称呼它:
You can do this:
and call it like this:
您可以嵌套使用语句:
You can nest using statements:
怎么样:
How about:
你是这个意思吗 ?
Is this what you mean ?