?!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
现有一个附加信息对象AttachedInfo,它里面分别有Info01、Info02.....Info10一共十个附加信息字D,现在参数传过来是一个string[]数组Q要怎么才能这个数l中的元素分别对应到q个对象中的各个字段呢,通过反射可以实玎ͼ即后期AttachedInfo中的Info字段增加Q或者说string[]中的元素个数与AttachedInfo中的Info字段个数不一致也没关pR?/span>
AttachedInfo ai = new AttachedInfo();
//通过反射AttachedInfo中的属性映成一个属性数l?/span>
Reflection.PropertyInfo[] propList = typeof(AttachedInfo).GetProperties();
//遍历该数l中的属?/span>
propList.ToList().ForEach(p =>
{
//Info开头的属性全都找出来
if (p.Name.StartsWith("Info"))
{
//因ؓ属性Info的后两位都是01?2的数字,因此可以L前缀Info,以此来对应string[]数组中的元素索引
int index = Convert.ToInt32(p.Name.TrimStart('I','n','f','o'));
//判断索引是否出了string[]数组
if (index <= smr.AttachedInfos.Count())
{
//l每个对象中的字D赋?/span>
p.SetValue(ai, smr.AttachedInfos[index - 1], null);
}
else
{
p.SetValue(ai, null, null);
}
}
});