1

我的代码是

    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;

还有什么更优雅的方式?

UPD:并且没有事件处理程序的 add_/remove_ 成员

4

1 回答 1

5

您可以查询已定义的访问器,然后排除这些访问器:

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;
                     });
于 2013-05-02T18:18:46.867 回答