繁体   English   中英

C#将方法作为参数传递给另一个方法

[英]C# Passing a method as a parameter to another method

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

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();
}

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

我怎么能做到这一点?

您可以使用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")); 

添加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); });

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

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

如果Method返回类型的值TR ,那么somethingFunc<TR> Func<T1, TR> Func<T1, T2, TR>

查看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)

看一下这篇文章的一些细节。 如果您希望您的方法获取参数,请使用Action,Action等。如果您希望它返回值,请使用Func等。这些泛型类有许多重载。

public delegate void MethodHandler(); // The type

public void ErrorDBConcurrency(DBConcurrencyException e, MethodHandler Method) // Your error function

ErrorDBConcurrency (e, new MethodHandler(myMethod)); // Passing the method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM