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

时间:2013-05-02 18:08:36

标签: c# linq reflection .net-3.5

我的代码是

    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:没有添加/删除事件处理程序的成员

1 个答案:

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