I have a destination class called Foo
with the following properties:
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
. 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.
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
:
PropertyInfo[] barProperties = new PropertyInfo[count];
To assign a value to the property, use SetValue
:
barProperties[i].SetValue(Foo, fileBars[i] );
I don't think you need to store the PropertyInfo
objects in an array; 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:
var myType = foo.GetType();
int barCount = 0;
foreach(string barValue in fileBars)
{
barCount++;
var barProperty = myType.GetProperty("Bar" + barCount);
barProperty.SetValue(foo, barValue, null);
}
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.