我有一个类对象列表
让我们说这个类的结构是这样的
class DataEntity
{
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
所以列表将是
List<DataEntity> list = new List<DataEntity>
所以这是我的问题我需要遍历列表并修改特定属性的值。但我不知道在运行时需要修改哪些属性。
所以假设有一个方法可以转换列表,而要修改的属性名称则作为字符串值传入
public List<DataEntity> Convert (List<DataEntity> list, string propertyName, string appendedValue)
{
}
所以我的问题是如何循环访问该列表,并且对于输入的propertyName,将additionalValue附加到该属性值
我知道我可以使用这样的反射获得proeprties值
Type type = dataEntity.GetType();
foreach (PropertyInfo pi in type.GetProperties())
{
}
但我不确定如何利用它来定位特定属性以便在运行时追加。
答案 0 :(得分:3)
你应该使用这样的东西:
PropertyInfo propertyInfo;
foreach (YourClass C in list)
{
propertyInfo = C.GetType().GetProperty(propertyName);
propertyInfo.SetValue(C, Convert.ChangeType(appendedValue, propertyInfo.PropertyType), null);
}
return list;
有关详细信息,请查看以下链接:Setting a property,Getting property value