如何通过反射获得所有没有getter和setter的公共静态成员



代码为

    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: And without add_/remove_ member of event handlers

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

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;
                     });

相关内容

  • 没有找到相关文章

最新更新