如何从变量名访问属性的子属性

时间:2014-12-31 23:24:39

标签: c# system.reflection

我想在模型中修改List中的属性。因为有很多这样的列表,我使用反射GetType()。GetProperty(propertyName)来做到如下,

public class SalesViewModel
{
public List<SelectListItem> SourceTypes0 { get; set; }
...
public List<SelectListItem> SourceTypes9 { get; set; }
}

SalesViewModel model = new SalesViewModel();
model.SourceTypes0 = from r in this._repository.SourceTypes
                    select new SelectListItem
                    {
                        Text = r.Name,
                        Value = SqlFunctions.StringConvert((double)r.SourceTypeID)
                    }).OrderBy(c => c.Text).ToList();
...
model.SourceTypes9 = from r in this._repository.SourceTypes
                    select new SelectListItem
                    {
                        Text = r.Name,
                        Value = SqlFunctions.StringConvert((double)r.SourceTypeID)
                    }).OrderBy(c => c.Text).ToList();

for (int i = 0; i < 10; i++)
{
string propertyName = "SourceTypes" + i.ToString();
var propInfo = model.GetType().GetProperty(propertyName);
if (propInfo != null)
{
propInfo.SetValue(model, "...", null);
}
}

如果我想修改model.SourceTypes0 [1] .Selected字段,问题是如何将propInfo转换为List或访问SourceTypes0 [1] .Selected。我试试

List<SelectListItem> propInfo = (List<SelectListItem>)model.GetType().GetProperty(propertyName);

但是它给出了错误

Cannot convert System.Reflection.PropInfo to System.Collections.Generic.List<System.Web.Mvc.SelectListItem>

我需要帮助。感谢。

1 个答案:

答案 0 :(得分:3)

方法GetProperty()返回PropertyInfo。如果要获取该属性的值,则需要调用其GetValue()方法:

var propInfo = model.GetType().GetProperty(propertyName);
var theList = (List<SelectListItem>)propInfo.GetValue(model);