【问题标题】:How can I dynamically select the property of an object in an object list I want to modify the value of [duplicate]如何在对象列表中动态选择对象的属性我想修改[重复]的值
【发布时间】:2015-01-25 08:13:54
【问题描述】:

我有一个类对象的列表

假设这个类的结构是这样的

    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 附加 appendedValue 到该属性值

我知道我可以像这样使用反射来获取属性值

 Type type = dataEntity.GetType();
 foreach (PropertyInfo pi in type.GetProperties())
 {    
 }

但我不确定如何利用它来定位特定属性以在运行时附加。

【问题讨论】:

  • 你看GetProperty()方法了吗?或者只是在GetProperties() 返回的PropertyInfo 对象数组中搜索具有您想要的名称的属性?您应该更具体地说明您已经完成了哪些研究、您发现了什么以及为什么您还不能使用这些信息来解决您的问题。
  • 将您的评论标记为非建设性的。下次要么回答问题,要么继续前进。由于 user3980820 非常友善,因此有大量数据可以帮助制定适当的响应。
  • 看到这将是一个有用的评论。当然比给我讲课更重要。

标签: c#


【解决方案1】:

你应该使用这样的东西:

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 propertyGetting property value

【讨论】:

  • 非常感谢您的回答。完美运行。
猜你喜欢
  • 2020-02-26
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多