【问题标题】:C# Passing a method as a parameter to another method [duplicate]C#将方法作为参数传递给另一个方法[重复]
【发布时间】:2011-07-21 20:00:34
【问题描述】:

我有一个发生异常时调用的方法:

public void ErrorDBConcurrency(DBConcurrencyException e)
{
    MessageBox.Show("You must refresh the datasource");
}

我想做的是向这个函数传递一个方法,所以如果用户点击是,那么这个方法就会被调用,例如

public void ErrorDBConcurrency(DBConcurrencyException e, something Method)
{
    if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
        Method();
}

方法可能有也可能没有参数,如果是这种情况,我也想传递它们。

我怎样才能做到这一点?

【问题讨论】:

标签: c# methods


【解决方案1】:

您可以使用Action 委托类型。

public void ErrorDBConcurrency(DBConcurrencyException e, Action method)
{
    if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
        method();
}

那么你可以这样使用它:

void MyAction()
{

}

ErrorDBConcurrency(e, MyAction); 

如果确实需要参数,可以使用 lambda 表达式。

ErrorDBConcurrency(e, () => MyAction(1, 2, "Test")); 

【讨论】:

    【解决方案2】:

    添加Action 作为参数:

    public void ErrorDBConcurrency(DBConcurrencyException e, Action errorAction)
    {
       if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
           errorAction()
    }
    

    然后你可以这样称呼它

    ErrorDBConcurrency(ex, () => { do_something(foo); });
    

    ErrorDBConcurrency(ex, () => { do_something_else(bar, baz); });
    

    【讨论】:

      【解决方案3】:

      您需要使用delegate 作为参数类型。

      如果Method 返回void,则somethingActionAction<T1>Action<T1, T2> 等(其中T1...Tn 是Method 的参数类型)。

      如果Method返回一个TR类型的值,那么something就是Func<TR>Func<T1, TR>Func<T1, T2, TR>

      【讨论】:

        【解决方案4】:

        查看 Func 和 Action 类。您可以使用以下方法实现此目的:

        public void ErrorDBConcurrency(DBConcurrencyException e, Action method)
        {
            if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
                method()
        }
        
        public void Method()
        {
            // do stuff
        }
        //....
        

        调用它使用

        ErrorDBConcurrency(ex, Method)
        

        查看this article 了解更多详情。如果你想让你的方法带参数,使用Action、Action等。如果你想让它返回一个值,使用Func等。这些泛型类有很多重载。

        【讨论】:

        • 应该是ErrorDBConcurrency(ex, Method)
        【解决方案5】:
        public delegate void MethodHandler(); // The type
        
        public void ErrorDBConcurrency(DBConcurrencyException e, MethodHandler Method) // Your error function
        
        ErrorDBConcurrency (e, new MethodHandler(myMethod)); // Passing the method
        

        【讨论】:

          猜你喜欢
          • 2013-07-01
          • 2018-08-08
          • 2016-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多