问题
I have the following code that is being copied and pasted in a number of places. The only difference being that there is a single call in the middle of the usings which changes. So I made a
public MyEntity Read(int id)
{
using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
{
sqlConn.Open();
return MyDataLayer.Select(sqlConn, id);
}
}
So I came up with this. However, my problem is how do i pass the sqlConn var to the call?
public TResult UsingSqlConnection<TResult>(Func<TResult> myFunction)
{
using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
{
sqlConn.Open();
return myFunction();
}
}
public MyEntity Read(int id)
{
return UsingSqlConnection(() => MyDataLayer.Read(id));
//PROBLEM: Read() requires sqlConn
}
Off the top of my head - it looks like instead of passing it as a param, that I need to create a property for SqlConn in MyDataLayer and assign it in the UsingSqlConnection method using an interface. While i wont rule out that refactor, I am wondering if I am missing something as this is my first attempt with Func delegates in this way.
回答1:
Func can have parameters:
public TResult UsingSqlConnection<TResult>(Func<SqlConnection, TResult> myFunc)
{
using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
{
sqlConn.Open();
return myFunc(sqlConn);
}
}
public MyEntity Read(int id)
{
return UsingSqlConnection((sqlConn) => MyDataLayer.Read(sqlConn, id));
}
来源:https://stackoverflow.com/questions/9253158/converting-using-sqlconnection-to-func-delegate