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

时间:2009-08-25 13:44:49

标签: c# .net function methods

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

示例:

Object "myObject" has two methods "method1" and "method2"

我希望有一个功能:

public bool myFunc(var methodOnObject)
{
   [code here]
   var returnVal = [run methodOnObject here]
   [code here]
   return returnVal;
}

所以在另一个函数中我可以做类似

的事情
public void overallFunction()
{
   var myObject = new ObjectItem();
   var method1Success = myFunc(myObject.method1);
   var method2Success = myFunc(myObject.method2);
}

3 个答案:

答案 0 :(得分:8)

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

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

private int DoSomething(string data)
{
    return -1;
}

委托声明将是......

public delegate int MyDelegate(string data);

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

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

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

myFunc(new MyDelegate(DoSomething));

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

myFunc(DoSomething); 

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

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

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

然后可以这样调用:

myFunc(s => return -1);

答案 1 :(得分:3)

是否真的需要明确的代表?也许这种方法可以帮助你:

private class MyObject
{
    public bool Method1() { return true; } // Your own logic here
    public bool Method2() { return false; } // Your own logic here
}

private static bool MyFunction(Func<bool> methodOnObject)
{
    bool returnValue = methodOnObject();
    return returnValue;
}    

private static void OverallFunction()
{
    MyObject myObject = new MyObject();

    bool method1Success = MyFunction(myObject.Method1);
    bool method2Success = MyFunction(myObject.Method2);
}

答案 2 :(得分:2)

是的,使用代表..

这是一个例子..

delegate string myDel(int s);
public class Program
{
    static string Func(myDel f)
    {
        return f(2);
    }

    public static void Main()
    {
        Test obj = new Test();
        myDel d = obj.func;
        Console.WriteLine(Func(d));
    }
}
class Test
{
    public string func(int s)
    {
        return s.ToString();
    }
}