开发者

Delegate pointing to multiple function with different signatures [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, 开发者_开发百科incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

How can a single delegate point to multiple function which will have different signature?

suppose i have a two functions whose signature is different.

private int Add(int x,int y)
{
   return (x+y);
}

private int MultiplyByTwo(int x)
{
   return (x*2);
}

please tell me is it possible with single delegate to point Add & multiple two different function at a time and function will call according to argument.

please discuss with code and also tell me how to perform the same job with func<> delegate.

thanks


This is not possible. The point of a delegate is to act as a strongly typed function pointer (loosely put), and nor will the runtime do any guessing as to what should be called depending on the parameters. If that is the type of functionality you are looking for, you might be interested in the dynamic keyword in C# 4.

All delegates inherit from a common delegate called Delegate, if that is the functionality you are looking for.

static void Main(string[] args)
{
    Delegate method1 = new Action<string>(PrintOneString);
    Delegate method2 = new Action<string, string>(PrintTwoString);
    method1.DynamicInvoke("Hello");
    method2.DynamicInvoke("Hello", "Goodbye");
}

public static void PrintOneString(string str)
{
    Console.WriteLine(str);
}

public static void PrintTwoString(string str1, string str2)
{
    Console.WriteLine(str1);
    Console.WriteLine(str2);
}


As the others already said, the signature of those methods are different. You can map the Add method to a Func<int, int, int> delegate:

Func<int, int, int> add = calculator.Add;

And you can map the MultiplyByTo method to a Func<int, int> delegate:

Func<int, int> multiply = calculator.MultiplyByTo;

You can map the Add method to a Func<int, int> delegate, but you need to fill in the missing argument:

Func<int, int> add5 = x => calculator.Add(x, 5);


Delegates are built to be strongly typed therefore you cannot achieve what you want by using them

You might should consider dynamic (.net 4.0)

-or-

using reflection. You could store the method name in a string variable and then invoke the method name by reflection.

Hope it helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜