[英]Reflection: How to get the class object via PropertyInfo
I have 2 classes.我有2节课。 ClassA has some objects of ClassB called Field01, Field02, ... Class A also has a list of ClassB items.
ClassA有一些ClassB 的对象,称为Field01、Field02、... Class A 也有一个 ClassB 项目的列表。
I know the name of the ClassB items and want to fill the ClassB items with the values from the list.我知道 ClassB 项目的名称,并想用列表中的值填充 ClassB 项目。
Example code:示例代码:
public class ClassA
{
public ClassB Field01 {get;set;}
public ClassB Field02 {get;set;}
//...
List<ClassB> myItems;
public void FillItems()
{
foreach(var item in MyItems)
{
// what I want in hardcode:
Field01.ValueA = MyItems[0].ValueA;
Field01.ValueB = MyItems[0].ValueB;
Field02.ValueA = MyItems[1].ValueA;
// ...
}
}
}
public class ClassB
{
public string ValueA {get;set;}
public string ValueB {get;set;}
}
In my case I'll have a counting variable which will create the Field01, Field02, Field03, ... names depending on how many items are in my List (there are always enough ClassB fields in ClassA to fill)在我的情况下,我将有一个计数变量,它将创建 Field01、Field02、Field03 ……名称,具体取决于我的 List 中有多少项目(ClassA 中总是有足够的 ClassB 字段来填充)
I know i can get the PropertyInfo of my ClassB items via name, but I don't know you I can access the ClassB attributes ValueA and ValueB我知道我可以通过名称获取我的 ClassB 项目的PropertyInfo ,但我不知道我可以访问 ClassB 属性 ValueA 和 ValueB
// If ClassB was just a string or object this would work
Type myType = typeof(ClassA);
PropertyInfo myPropInfo = myType.GetProperty("Field01");
myPropInfo.SetValue(this, "Hello", null);
Since you know the declaring type of the properties is ClassB
, you can get the PropertyInfo
of ValueA
and ValueB
.由于您知道属性的声明类型是
ClassB
,因此您可以获取ValueA
和ValueB
的PropertyInfo
。 Then, you need to get the value of FieldXX
(not set it!) and set ValueA
and ValueB
.然后,您需要获取
FieldXX
的值(不要设置它!)并设置ValueA
和ValueB
。
We are going to be dealing with multiple Type
, PropertyInfo
and object
objects, so you should name your variables appropriately, instead of just myPropInfo
or myType
.我们将要处理多种
Type
, PropertyInfo
和object
对象,所以你应该适当命名的变量,而不是仅仅myPropInfo
或myType
。
for (int i = 0 ; i < MyItems.Count ; i++) {
var classAType = typeof(ClassA);
var classBType = typeof(ClassB);
var fieldInfo = classAType.GetProperty("Field" + $"{i}".PadLeft(2, '0'));
var fieldValue = fieldInfo.GetValue(this);
var valueAInfo = classBType.GetProperty(nameof(ClassB.ValueA));
var valueBInfo = classBType.GetProperty(nameof(ClassB.ValueB));
valueAInfo.SetValue(fieldValue, valueAInfo.GetValue(MyItems[i]));
valueBInfo.SetValue(fieldValue, valueBInfo.GetValue(MyItems[i]));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.