[英]How can I use reflection in C# to find all the members of a class that meet the requirements of a specific delegate?
我有一个带有一堆公共方法的类,我想对此进行反思,以找到可以用作特定委托的成员方法集。
例如:
delegate void InterestingFunc(int i);
class Entity
{
public void F();
public void G();
public void H(int i);
public void X(int i);
}
我可以使用Type.FindMembers()拉出集合{H,X}吗? 如果是这样,怎么办? 有没有更好的办法?
Type中没有固有的查询支持,该查询将基于委托签名来查找方法。 您将需要手工编写一个搜索方法,该方法手动遍历方法和属性,将签名与提议的委托人的签名进行比较。
这本身是一项不平凡的操作,因为您需要在解决方案中考虑泛型。
这本身是一项不平凡的操作,因为您需要在解决方案中考虑泛型。
100%正确-更不用说ref
/ out
参数, param[]
修饰符以及不安全的指针了。
一个非最佳选择是将Delegate.CreateDelegate
应用于Entity
每个方法,请注意构造失败的时间。 失败表示不兼容的方法。
同样,您可能需要做一些工作来处理通用方法。
这是一个开始:
MethodInfo[] FindMethods(Type delegateType, Type sourceType)
{
var dInfo = delegateType.GetMethod("Invoke");
var dParamTypes = delegateInfo.GetParameters().Select(p=>p.ParameterType);
var methods = from methodInfo in sourceType.GetMethods()
let mParamTypes = methodInfo.GetParameters()
.Select(p=>p.ParameterType)
where methodInfo.ReturnType == delegateInfo.ReturnType
&& mParamTypes.SequenceEqual(dParamTypes)
select methodInfo;
return methods.ToArray();
}
可以扩展它以考虑泛型,引用/输出参数以及其他任何内容。 测试驱动的开发在这里特别有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.