简体   繁体   中英

Using Common Delegate to call multiple methods across different classes

I need to pass a delegate and a method name that the delegate should invoke as an argument to a class constructor how do i do this ??

ie if

public delegate object CCommonDelegate();

is my delegate and say it can call any methods following this signature

string Method1();

object Method2();

class X
{
    public X(CCommonDelegate,"MethodName to invoke"){}  //how to pass the Method name here..

}

PS : Ignore the access modifiers

A delegate is a variable that holds something that can be called. If X is a class that needs to be able to call something, then all it needs is the delegate:

public delegate object CommonDelegate();

class X
{
    CommonDelegate d;

    public X(CommonDelegate d)
    {
        this.d = d; // store the delegate for later
    }
}

Later it can call the delegate:

var o = d();

By the way, you don't need to define such a delegate. The type Func<Object> already exists and has the right structure.

To construct X given your two example methods:

string Method1()
object Method2()

You could say

var x = new X(obj.Method2);

Where obj is an object of the class that has Method2 . In C# 4 you can do the same for Method1 . But in 3 you'll need to convert using a lambda:

var x = new X(() => obj.Method1);

This is because the return type is not exactly the same: it's related by inheritance. This will only work automatically in C# 4, and only if you use Func<object> .

why not just have your constructor take an Func< object>

public class x
{
     public x(Func<object> func)
     {
           object obj = func();
     }
}

then

x myX = new x(()=> "test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM