Reputation:
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.
Upvotes: 0
Views: 350
Reputation: 30022
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; }
}
Upvotes: 2