简体   繁体   中英

How can I use reflection in C# to get object value from a member of a class?

How can I use reflection in C# to get object value from a member of a class?

I have:

public class Class1 {
   public int field1;
   public String field2;
}

public class Class2 {
   public ind code;
   public Class1 classRef;
}

I want get the list of members the "classRef" value.

I think this is close

var c2 = new Class2 
                { 
                  code = 3; 
                  Class1 = new Class1 
                  {
                      field1 = 7; 
                      field2 = "class 1"
                  }
                };

var fields = c2.GetType().GetFields();
var field = fields.Where(fi=>fi.Name == "classRef").FirstOrDefault();
Assert.True(field != null);
var value = field.GetValue(c2) as Class1;

Assert.True(value != null);
Assert.True(value.field1 == 7);
Assert.True(value.field2 == "class 1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM