将成员信息反射到Func< T1,T2>. [英] Reflection MemberInfo to Func<T1, T2>
问题描述
我正在寻找一种将MemberInfo
实例转换为"Func"类型的方法(以便稍后通过lambda表达式使用).
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);
使用反射,我以某种方式获取了MemberInfo
"mi"的实例,现在我想将其转换为Func<int, bool>;
类型.像这样:
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);
有办法吗?
ps.马克·格雷威尔(Marc Grawell)的答案解决了我的问题,无需进一步评论
ps. Marc Grawell's answer resolves my issue, no need for further comments
推荐答案
Func<int,bool> f = Delegate.CreateDelegate(
typeof(Func<int,bool>), target, (MethodInfo)mi);
请注意,由于func
是非static
方法,因此target
是您要使用的 object .如果它是static
方法,则可以忽略(或传递null
).另外,如果将其设为Func<Foo, int, bool>
,其中Foo
是声明func
的类型,则可以省略target
(或传递null
).
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
.
但是!!!注意,在创建lambda表达式方面,具有Func<int,bool>
在很大程度上没有意义; lambda表达式很少使用委托.
However!!! Note that having a Func<int,bool>
is largely meaningless in terms of creating a lambda expression; lambda expressions rarely use delegates.
这篇关于将成员信息反射到Func< T1,T2>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!