How to list all Variables of Class

前端 未结 5 1818
情书的邮戳
情书的邮戳 2020-11-27 05:49

Is there a way to list all Variables (Fields) of a class in C#. If yes than could someone give me some examples how to save them in a List and get them maybe us

5条回答
  •  天命终不由人
    2020-11-27 06:36

    This will list the names of all fields in a class (both public and non-public, both static and instance fields):

    BindingFlags bindingFlags = BindingFlags.Public |
                                BindingFlags.NonPublic |
                                BindingFlags.Instance |
                                BindingFlags.Static;
    
    foreach (FieldInfo field in typeof(TheClass).GetFields(bindingFlags))
    {
        Console.WriteLine(field.Name);
    }
    

    If you want to get the fields based on some object instance instead, use GetType instead:

    foreach (FieldInfo field in theObject.GetType().GetFields(bindingFlags))
    {
        Console.WriteLine(field.Name);
    }
    

提交回复
热议问题