简体   繁体   中英

Add ListItem to a Field of type List<MyClass> using Reflection

I have the following problem: I want to Add a List item to a Collection to a field of a class.

To be clear: I have a class:

class MyClass {
   List<MyStruct> myList1;
   List<MyStruct> myList2;
}

struct MyStruct {
   string foo { get; set; }
   string bar { get; set; }
}

What i want is to add a MyStruct to the List myList1 by getting the field through:

MyClass blub = new MyClass();
(blub.GetType().GetField("myList1") as List<MyStruct>).Add(new Mystruct {
      foo = "foo";
      bar = "bar";
   });

Is there a possibility to achieve this in any way? The main problem is that i have to identify my field by a string.

Using Reflection you need to specify the BindingFlags to retrieve private fields. When you get it, you need to use FieldInfo.SetValue and FieldInfo.GetValue . Like this:

MyClass blub = new MyClass();

var field = blub.GetType().GetField("myList1", BindingFlags.NonPublic | BindingFlags.Instance);
List<MyStruct> value = field.GetValue(blub) as List<MyStruct>;

if (value == null)
    value = new List<MyStruct>();

value.Add(new MyStruct { foo = "foo", bar = "bar" });

field.SetValue(blub, value);

Note that you need to modify the properties of your struct to be public :

struct MyStruct
{
    public string foo { get; set; }
    public string bar { get; set; }
}

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