是否可以将对象的方法发送给函数?

Chr*_*Dog 2 .net c# methods function

我想知道将对象的方法发送到函数是否可能(以及语法是什么).

例:

Object "myObject" has two methods "method1" and "method2"
Run Code Online (Sandbox Code Playgroud)

我希望有一个功能:

public bool myFunc(var methodOnObject)
{
   [code here]
   var returnVal = [run methodOnObject here]
   [code here]
   return returnVal;
}
Run Code Online (Sandbox Code Playgroud)

所以在另一个函数中,我可以做类似的事情

public void overallFunction()
{
   var myObject = new ObjectItem();
   var method1Success = myFunc(myObject.method1);
   var method2Success = myFunc(myObject.method2);
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*son 8

是的,您需要使用委托.委托与C/C++中的函数指针非常类似.

您首先需要声明委托的签名.说我有这个功能:

private int DoSomething(string data)
{
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

代表声明将是......

public delegate int MyDelegate(string data);
Run Code Online (Sandbox Code Playgroud)

然后你可以用这种方式声明myFunc ..

public bool myFunc(MyDelegate methodOnObject)
{
    [code here]
    int returnValue = methodOnObject("foo");
    [code here]
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过以下两种方式之一来调用它:

myFunc(new MyDelegate(DoSomething));
Run Code Online (Sandbox Code Playgroud)

或者,在C#3.0及更高版本中,您可以使用...的简写

myFunc(DoSomething); 
Run Code Online (Sandbox Code Playgroud)

(它只是自动将所提供的函数包装在该委托的默认构造函数中.这些调用在功能上是相同的).

如果您不关心为简单表达式实际创建委托或实际函数实现,则以下内容也适用于C#3.0:

public bool myFunc(Func<string, int> expr)
{
    [code here]
    int returnValue = methodOnObject("foo");
    [code here]
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样调用:

myFunc(s => return -1);
Run Code Online (Sandbox Code Playgroud)