Can I send a method of an object to a function?

I am wondering if it is possible (and what the syntax is) to send a method of a function object.

Example:

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

      

I would like to have a function line by line:

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

      

So in another function, I could do something like

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

      

+2


source to share


3 answers


Is there a need for explicit delegates? Maybe this approach will help you:



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

      

+3


source


Yes, you need to use a delegate. Delegates are pretty similar to function pointers in C / C ++.

First you need to declare the signature of the delegate. Let's say I have this function:

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

      

The delegate declaration will be ...

public delegate int MyDelegate(string data);

      

Then you can declare myFunc this way.

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

      

Then you can call it in one of two ways:



myFunc(new MyDelegate(DoSomething));

      

Or, in C # 3.0 and later, you can use shorthand ...

myFunc(DoSomething); 

      

(It just terminates the provided function in the default constructor for that delegate automatically. The calls are functionally identical).

If you don't want to create a delegate or actual function implementation for simple expressions, the following will also work in C # 3.0:

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

      

What then could be called like this:

myFunc(s => return -1);

      

+8


source


Yes, using delegates ..

Here's an example.

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

      

+2


source







All Articles