Retrieving class attributes and their values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ullner
    New Member
    • Mar 2008
    • 4

    Retrieving class attributes and their values

    I have multiple classes, named A, B and C. I want to get the attributes of all classes and their values. How can I do this?

    I can get the attribute names of (eg) the class "A" by;
    Code:
    Type classType = A.GetType();
    PropertyInfo[] a_pi = classType.GetProperties();
    foreach (PropertyInfo pi in a_pi)
         Console.WriteLine(pi.Name);
    But I'm not able to get their values.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Hmm, there must be some way, because when you set an object as the datasource for a datatable, any public properties become columns and the values of those properties are inserted into them.

    I think you would use:
    Code:
    classType.InvokeMember(pi.Name, BindingFlags.Default, null, myA, myArgs);
    You will have to look up the arguments as I just kind of picked them at random.

    Comment

    • ullner
      New Member
      • Mar 2008
      • 4

      #3
      Thanks. I used your solution (a bit modified);
      Code:
                  Type classType = A.GetType();
                  PropertyInfo[] a_pi = classType.GetProperties();
                  foreach (PropertyInfo pi in a_pi)
                  {       
                      Object obj = classType.InvokeMember(null,
                                  BindingFlags.DeclaredOnly |
                                  BindingFlags.Public | BindingFlags.NonPublic |
                                  BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
                      
                      object values =  classType.InvokeMember(pi.Name,
                                  BindingFlags.DeclaredOnly |
                                  BindingFlags.Public | BindingFlags.NonPublic |
                                  BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
      
                      Console.WriteLine(values);
      The problem is that if I use an instance of the type A, instead of directly A, I get the default values for that class, and not the modified values.
      (That is, if I do
      Code:
      A a = new A();
      a.someAttribute = someVal;
      Type classType = a.getType();
      ...
      )

      Any suggestions?

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        So use the instance of A you want and don't create a new instance. I think that is stated somewhere in those bindingflags.

        Comment

        Working...