我的代码是
var memberList = from member in type.GetMembers(BindingFlags.Static | BindingFlags.Public)
.Where(m => !(m.Name.Contains("get_") || m.Name.Contains("set_") ||
m.Name.Contains("add_") || m.Name.Contains("remove_")) )
select member;
更优雅的方式?
UPS:没有添加/删除事件处理程序的成员
答案 0 :(得分:4)
您可以查询已定义的访问者,然后排除这些访问者:
var propertyAccessors = type.GetProperties(BindingFlags.Static | BindingFlags.Public)
.SelectMany(p => p.GetAccessors())
.Cast<MemberInfo>();
var eventAccessors = type.GetEvents(BindingFlags.Static | BindingFlags.Public)
.SelectMany(e => new[] {
e.GetAddMethod(true),
e.GetRemoveMethod(true)
})
.Cast<MemberInfo>();
var accessors = propertyAccessors.Concat(eventAccessors);
var memberList = type.GetMembers(BindingFlags.Static | BindingFlags.Public)
.Except(accessors);
您可能只能过滤掉那些没有特殊名称的方法(由MethodBase.IsSpecialName
定义。
var memberList = type.GetMembers(BindingFlags.Static | BindingFlags.Public)
.Where(m => {
var method = m as MethodBase;
return method == null || !method.IsSpecialName;
});