C#将一个方法作为参数传递给另一个方法 [英] C# Passing a method as a parameter to another method
本文介绍了C#将一个方法作为参数传递给另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个在发生异常时调用的方法:
I have a method that is called when an exception occurs:
public void ErrorDBConcurrency(DBConcurrencyException e)
{
MessageBox.Show("You must refresh the datasource");
}
我想做的就是将此函数传递给方法,因此,如果用户单击是",则该方法称为例如.
What i would like to do is pass this function a method so if the user clicks Yes then the method is called e.g.
public void ErrorDBConcurrency(DBConcurrencyException e, something Method)
{
if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
Method();
}
如果有这种情况,我也想传递参数,则该方法可能有也可能没有参数.
The Method may or may not have parameters, if this is the case i would like to pass them too.
我该如何实现?
推荐答案
You can use the Action
delegate type.
public void ErrorDBConcurrency(DBConcurrencyException e, Action method)
{
if (MessageBox.Show("You must refresh the datasource") == DialogResult.OK)
method();
}
然后您可以像这样使用它:
Then you can use it like this:
void MyAction()
{
}
ErrorDBConcurrency(e, MyAction);
如果确实需要参数,则可以使用lambda表达式.
If you do need parameters you can use a lambda expression.
ErrorDBConcurrency(e, () => MyAction(1, 2, "Test"));
这篇关于C#将一个方法作为参数传递给另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文