How to get the parameter and return types of a delegate from its Type?

  • Thread starter Thread starter Ruediger Klaehn
  • Start date Start date
R

Ruediger Klaehn

I have written an arithmetic expression compiler. Now that it is finished I
would like to give it a nice interface. Currently I have this interface:

delegate double Function(double x);
class ArithmeticExpression
{
public static Function Compile(string text);
...
}

This can be used like this:

Function f=ArithmeticExpression.Compile("x*x");
Console.WriteLine(f(2)); //gives 4

Obviously this only supports one parameter, which is always of type double
and called x.

I would like to do a similar interface for functions with multiple
parameters, but I do not want to have to define a delegate for each number
of parameters. So I would like to do it like this:

class ArithmeticExpression
{
public static Delegate Compile(string text,Type delegateType);
}

This could then be used like this:

delegate double Function2(double x,double y);
Function2 g=ArithmeticExpression.Compile("x*y",typeof(Function2));
Console.WriteLine(g(1,2));

To do it that way I need to get the number and type of parameters as well as
the return type from the delegate type. I looked at System.Type, but found
no obvious way to do this.

Is this possible? Or is there a better way to achieve a simple syntax like
the one shown above?

best regards

Rüdiger
 
You might want to take a look at the params keyword in C# that allows
you to have variable number of arguments.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfparams.asp

Also you can get the information regarding the params and return type
of the method by looking at the properties and methods of the MethodInfo
class which can be accessed via the Delegate.Method property

For e.g.

Type returnType = delegate.Method.ReturnType;

Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
 
Sijin said:
You might want to take a look at the params keyword in C# that allows
you to have variable number of arguments.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfparams.asp
I know this.I will probably provide a method like this as well. But
since my compiled code uses ldarg_0 etc. opcodes I can not use this
without providing a wrapper.
Also you can get the information regarding the params and return type
of the method by looking at the properties and methods of the MethodInfo
class which can be accessed via the Delegate.Method property

For e.g.

Type returnType = delegate.Method.ReturnType;
This does not do me any good since I do not have an instance of the
delegate. But I figured out how to do it just minutes after posting this
question: I just have to get the MethodInfo for the dynamically created
metohd "Invoke" using MethodInfo mi=delegateType.GetMethod("Invoke").
This methodinfo contains all the Info I need to create a matching method.
 
Back
Top