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

use*_*261 1 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;
Run Code Online (Sandbox Code Playgroud)

有什么更优雅的方式?

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

cdh*_*wie 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);
Run Code Online (Sandbox Code Playgroud)

您也许可以只过滤掉那些没有特殊名称(由MethodBase.IsSpecialName.

var memberList = type.GetMembers(BindingFlags.Static | BindingFlags.Public)
                     .Where(m => {
                         var method = m as MethodBase;
                         return method == null || !method.IsSpecialName;
                     });
Run Code Online (Sandbox Code Playgroud)