[英]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: 我想要的是通过获取字段来将MyStruct添加到列表myList1中:
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. 使用反射,您需要指定
BindingFlags
来检索私有字段。 When you get it, you need to use FieldInfo.SetValue
and FieldInfo.GetValue
. 获取时,需要使用
FieldInfo.SetValue
和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 : 请注意,您需要将结构的属性修改为public:
struct MyStruct
{
public string foo { get; set; }
public string bar { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.