How to list all Variables of Class

前端 未结 5 1768
情书的邮戳
情书的邮戳 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:31

    Your question isn't perfectly clear. It sounds like you want the values of the fields for a given instance of your class:

    var fieldValues = foo.GetType()
                         .GetFields()
                         .Select(field => field.GetValue(foo))
                         .ToList();
    

    Note that fieldValues is List. Here, foo is an existing instance of your class.

    If you want public and non-public fields, you need to change the binding flags via

    var bindingFlags = BindingFlags.Instance |
                       BindingFlags.NonPublic |
                       BindingFlags.Public;
    var fieldValues = foo.GetType()
                         .GetFields(bindingFlags)
                         .Select(field => field.GetValue(foo))
                         .ToList();
    

    If you merely want the names:

    var fieldNames = typeof(Foo).GetFields()
                                .Select(field => field.Name)
                                .ToList();
    

    Here, Foo is the name of your class.

    提交回复
    热议问题