[英]Using C# Reflection to assign collection of variable size to class properties
I have a destination class called Foo
with the following properties: 我有一个名为
Foo
的目标类,具有以下属性:
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
public string Bar4 { get; set; }
public string Bar5 { get; set; }
public string Bar6 { get; set; }
I'm reading in a file that could have any number of "Bars" which I read into a collection called fileBars
. 我正在读取一个文件,该文件可以具有任意数量的“ Bars”,并将其读取到名为
fileBars
的集合中。 I need to find out how to use Reflection to iterate over fileBars
and assign the first one to Bar1
, the second one to Bar2
, etc. 我需要找出如何使用反射来遍历
fileBars
并指定第一个Bar1
,第二个到Bar2
等。
I've tried several things I've found online, most recently playing with what's shown below, but I haven't had any luck. 我已经尝试了一些在网上找到的东西,最近一次是按照下面显示的方法进行的,但是我没有任何运气。 Can someone who is familiar with Reflection point me in the right direction?
熟悉反射的人能指出我正确的方向吗?
var count = fileBars.Count();
var myType = Foo.GetType();
PropertyInfo[] barProperties = null;
for (var i = 0; i < count; i++)
{
barProperties[i] = myType.GetProperty("Bar" + i + 1);
}
You need to initialize barProperties
: 您需要初始化
barProperties
:
PropertyInfo[] barProperties = new PropertyInfo[count];
To assign a value to the property, use SetValue
: 要将值分配给属性,请使用
SetValue
:
barProperties[i].SetValue(Foo, fileBars[i] );
I don't think you need to store the PropertyInfo
objects in an array; 我认为您不需要将
PropertyInfo
对象存储在数组中; you can just assign the values as you go: 您可以随便分配值:
var count = fileBars.Count();
var instance = new Foo();
for (var i = 1; i <= count; i++)
{
var property = typeof(Foo).GetProperty("Bar" + i);
if(property != null)
property.SetValue(instance, fileBars[i - 1];
else
// handle having too many bars to fit in Foo
}
Unless you need to keep all the properties you find for later, you don't need the barProperties
array: 除非以后需要保留找到的所有属性,否则不需要
barProperties
数组:
var myType = foo.GetType();
int barCount = 0;
foreach(string barValue in fileBars)
{
barCount++;
var barProperty = myType.GetProperty("Bar" + barCount);
barProperty.SetValue(foo, barValue, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.