使用反射修改字符串列表

时间:2014-12-02 04:46:47

标签: c# string list reflection

说,我有一个类User,它有(string FirstName,List siblings) 我想修改用户的属性。

我们假设我想用b而不是a替换字符串。

用户:{ 名字:“Rager”, 兄弟姐妹 : { “斯大林”, “马克思” }}

使用反射我需要读取单个字符串,以下将是输出对象。

用户:{ 名字:“Rbger”, 兄弟姐妹 : { “stblin” “Mbrx” }}

让我们考虑以下功能

private object modifyObject(object t){
   foreach(var propertyInfo in t.GetType.GetProperties(){
      var stringToBeModified = propertyInfo.GetValue(t,null);
      propertyInfo.SetValue(t, stringToBeModified.replace("a","b"),null)
   }
}

修改firstName时,上面的代码工作正常。但是不知道如何修改兄弟姐妹中的字符串。

我以为我会使用第3个属性(索引属性的可选索引值)。但看起来整个房产都没有编入索引。 对于兄弟姐妹,propertyInfo.GetValue(t,null)给出2个字符串。

[0] -- stalin
[1]  -- Marx. 

有人能告诉我如何在使用propertyInfo.GetValue(t,null)获取值后修改上述2个字符串吗?

1 个答案:

答案 0 :(得分:1)

您可以简单地将值转换为List<string>并根据需要进行更新

例如

List<string> list = (List<string>)propertyInfo.GetValue(t,null);
list[0] = list[0].replace("a","b");

以上示例假设属于List<string>类型的兄弟属性的propertyInfo,您可以根据需要进行调整。