![](/img/trans.png)
[英]C#: passing a method with variable parameters as parameter of another method
[英]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); });
查看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.