etwas77
etwas77

Reputation: 514

Reflection MemberInfo to Func<T1, T2>

I'm looking for a method to convert instance of MemberInfo to "Func" type (to use it through lambda expression later).

Lets, say I have a member function of type

public bool func(int);

Using reflection, I somehow get instance of MemberInfo "mi", now i want to convert it to Func<int, bool>; type. something like:

Func<int, bool f = myType.GetMember(mi.Name);

Is there a way to do it?

ps. Marc Grawell's answer resolves my issue, no need for further comments

Upvotes: 5

Views: 901

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062492

Func<int,bool> f = (Func<int,bool>)Delegate.CreateDelegate(
           typeof(Func<int,bool>), target, (MethodInfo)mi);

or on more recent frameworks:

var f = mi.CreateDelegate<Func<int,bool>>(target);

Note here that target is the object you want to use, since func is a non-static method. If it was a static method, you can omit that (or pass null). Alternatively, you can omit target (or pass null) if you make it a Func<Foo, int, bool> where Foo is the type that declares func.

However!!! Note that having a Func<int,bool> is largely meaningless in terms of creating a lambda expression; lambda expressions rarely use delegates.

Upvotes: 6

Related Questions