Reputation: 153
SO lets say in my class I have:
public delegate bool MyFunc(int param);
How can I then do this
someObj.PassMeADelegateToExamine(this.MyFunc); // not possible!?!
SO that I can examine the delegate and perhaps use reflection or something idk to find out it's return type and any params it might have?
Basically if I can transform it into an (uncallable) Action object that woul dbe grand
Upvotes: 2
Views: 473
Reputation: 15515
A delegate declaration is a type declaration, just like struct
and class
. So you can use
typeof(MyFunc)
To find the delegate's return type and arguments, you must look at the delegate type's Invoke
method:
MethodInfo invokeMethod = typeof(MyFunc).GetMethod("Invoke");
Type returnType = invokeMethod.ReturnType;
ParameterInfo[] parameterInfos = invokeMethod.GetParameters();
A delegate is pretty much a class with some conventional methods like Invoke
. When you use a delegate instance like so
func(args)
This is translated internally to
func.Invoke(args)
Which is why there is no special DelegateInfo type in the reflection namespace: the Invoke
method's MethodInfo tells you all you need.
Now, if you'd want to call a delegate instance dynamically, you can either use reflection and call Invoke
on your MethodInfo or make sure your delegate variable is typed as Delegate, which gives you access to the DynamicInvoke
method:
Delegate func = ...;
object result = func.DynamicInvoke(arg1, arg2);
Upvotes: 1
Reputation: 564413
The "prototype" is just a new Type definition - it's not an actual instance that you would use directly. In your case, MyFunc is the delegate Type
, not an actual delegate.
You could do:
void PassMeADelegateTypeToExamine(Type type) { ... }
And then call it:
someObj.PassMeADelegateTypeToExamine(MyFunc);
Upvotes: 2