Question

This is a C#.net question for Objective-C developers who also work with C#.Net

As you know, Objective-C you can parse a method name to a Selector; and the method can also belong to an outside class.

I would like to be able to use this type of method in C#.Net as it would be a lot cleaner than creating loads of Events which can become messy and hard to manage.

If this is possible, how can I achieve this? Thank you!

Example:

public class Main
{
    public void MyProcess(Callback toMethod)
    {
        // do some fancy stuff and send it to callback object       
        toMethod(result);
    }
}

public class Something
{
    public void RunMethod()
    {
        MyProcess(Method1);
        MyProcess(Method2);
    }

    private void Method1(object result)
    {
        // do stuff for this callback
    }

    private void Method2(object result)
    {
        // do stuff for this callback
    }
}
Was it helpful?

Solution

I don't know Objective-C, but I think you want something like this:

public class Main
{
    public void MyProcess(Action<object> toMethod, object result)
    {
        // do some fancy stuff and send it to callback object       
        toMethod(result);
    }
}

public class Something
{
    public void RunMethod()
    {
        object result = new object();
        MyProcess(Method1, result);
        MyProcess(Method2, result);
    }

    private void Method1(object result)
    {
        // do stuff for this callback
    }

    private void Method2(object result)
    {
        // do stuff for this callback
    }
}

OTHER TIPS

You would have to use Delegates. Based on the code in your question, you would declare a delegate:

public delegate void MethodDelegate(object result);

The signature of the process method changes to the following:

public void MyProcess(MethodDelegate toMethod)
{
    // do some fancy stuff and send it to callback object       
    toMethod(result);
}

And then you would call process

public void RunMethod()
{
    MyProcess(new MethodDelegate(Method1));
    MyProcess(new MethodDelegate(Method1));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top