代码之家  ›  专栏  ›  技术社区  ›  FrenkyB

从结构类型获取静态属性

  •  0
  • FrenkyB  · 技术社区  · 6 年前

    我需要的是列出这个结构的所有属性(从结构而不是从这个结构的实例)。这可能吗?

    CommUser.GetType.GetProperties();

    public struct CommUser
    {
       public static string pcUSER_URI_R97 {get;set;}        
       public static string pcUSER_URI_R98 {get;set;}   
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   TheGeneral    6 年前

    你差点就吃到了

    var names = typeof(CommUser).GetProperties(BindingFlags.Static|BindingFlags.Public)
                                .Select(x => x.Name);    
    foreach (var name in names)
        Console.WriteLine(name);
    

    输出

    pcUSER_URI_R97
    pcUSER_URI_R98
    

    Full Demo Here


    额外资源

    typeof (C# Reference)

    用于获取类型的System.Type对象

    GetProperties(BindingFlags)

    当前类型,使用指定的绑定约束。

    BindingFlags Enum

    • Public 指定要在搜索中包含公共成员

    • Static