开发者

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 con开发者_开发技巧structor how do i do this ??

i.e 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..

}

P.S : 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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜