将委托转换为Action <t>(Action <t1,t2>)</t1,t2> </t>

时间:2012-09-17 14:37:56

标签: c# generics .net-3.5

我有一个DB类,可以进行如下所有的DB调用:

public delegate void Part1_Callback(string message);
public delegate void Part2_Callback(DataTable dt);
public delegate void Part3_Callback(DataTable dt, int x, int y);
public delegate void ErrorHandler(string message);

public class CommandAndCallback<TCallback>
{
    public SqlCommand Sql { get; set; }
    public TCallback Callback { get; set; }
    public ErrorHandler Error { get; set; }
}

class DB : SingletonBase<DB>
{
    public static readonly string SqlConnectionString  = @"Data Source=MyDB;Initial Catalog=Stats;Integrated Security=True;Asynchronous Processing=true;";

    private DB()
    {
    }

    public void Part2(Part2_Callback callback, ErrorHandler error)
    {
        SqlConnection conn = new SqlConnection(SqlConnectionString);
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "Part2";

        try
        {
            conn.Open();
        }
        catch (Exception ex)
        {
            error(ex.ToString());
            return;
        }

        CommandAndCallback<Part2_Callback> ar = new CommandAndCallback<Part2_Callback>() { Callback = callback, Error = error, Sql = cmd };
        IAsyncResult result = cmd.BeginExecuteReader(new AsyncCallback(Part2_Handler), ar, CommandBehavior.CloseConnection);
    }

    private void Part2_Handler(IAsyncResult result)
    {
        DataTable dt = new DataTable();
        CommandAndCallback<Part2_Callback> ar = (CommandAndCallback<Part2_Callback>)result.AsyncState;
        SqlDataReader dr;

        if (result.IsCompleted)
        {
            dr = ar.Sql.EndExecuteReader(result);
        }
        else
            dr = null;

        dt.Load(dr);
        dr.Close();
        dt.Columns[3].ReadOnly = false;
        ar.Callback(dt);
    }
}

在我的主要课程中,我正在使用它:

    private void Form1_Enter(object sender, EventArgs e)
    {
        showStatus("Loading");
        DB.Instance.Part2(Part2_OK, ErrorHandler);
    }
    private void ErrorHandler(string msg)
    {
        hideStatus();
        viewStack1.InvokeIfRequired(c => { c.moveToFirst(); });
        //MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    private void Part2_OK(DataTable dt)
    {
        dataGridView1.InvokeIfRequired(c =>
        {
            c.DataSource = dt;
        });
    }

现在我在我的数据库类中有3个方法返回3个不同的数据集,对于我必须声明委托的每种类型。
如果将来我会添加更多方法,那么我将不得不添加更多代表。

我可以删除代理人的使用情况吗?我想简化我的类的构建,以便添加新方法。

我需要的是能够像这样调用我的DB类:

DB.Instance.PartX(PartX_OK, ErrorHandler);

PartX声明如图所示

private void PartX_OK(DataTable dt, int x, int y, ...)
{
//logic here
}

可以Action<T>使用它,所以我可以用多个参数调用我的处理程序吗?如果是,那么如何?

3 个答案:

答案 0 :(得分:2)

Action个类,最多16个通用参数,您可能会找到满足您需求的类;)。请参阅MSDN page

和调用

DB.Instance.PartX((p1, p2, p3, p4) => { ... }, ErrorHandler);

答案 1 :(得分:2)

是的,我的意思是回到你之前的问题,所以你的功能将成为

public void Part2(Action<DataTable> callback, ErrorHandler error)
{
    SqlConnection conn = new SqlConnection(SqlConnectionString);
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "Part2";

    try
    {
        conn.Open();
    }
    catch (Exception ex)
    {
        error(ex.ToString());
        return;
    }

    CommandAndCallback<Action<DataTable>> ar = new CommandAndCallback<Action<DataTable>>() { Callback = callback, Error = error, Sql = cmd };
    IAsyncResult result = cmd.BeginExecuteReader(new AsyncCallback(Part2_Handler), ar, CommandBehavior.CloseConnection);
}

        private void Part2_Handler(IAsyncResult result)
    {
        DataTable dt = new DataTable();
        CommandAndCallback<Action<DataTable>> ar = (CommandAndCallback<Action<DataTable>>)result.AsyncState;
        SqlDataReader dr;

        if (result.IsCompleted)
        {
            dr = ar.Sql.EndExecuteReader(result);
        }
        else
            dr = null;

        dt.Load(dr);
        dr.Close();
        dt.Columns[3].ReadOnly = false;
        ar.Callback(dt);
    }

答案 2 :(得分:2)

  1. Part1_Callback将与Action<string>
  2. 等效
  3. Part2_Callback将与Action<DataTable>
  4. 等效
  5. Part3_Callback将与Action<DataTable, int, int>
  6. 等效
  7. ErrorHandler将与Action<string>
  8. 等效

    只需使用这些类型代替现有的每个代表。

    几乎没有案例你需要定义自己的代表。如果您有> 16个参数,ref/out参数,params参数或可选参数,那么您可能没有Action / Func重载,但这并不是特别常见。