【问题标题】:Modifying the string list using reflection使用反射修改字符串列表
【发布时间】:2014-12-02 04:46:47
【问题描述】:

说,我有一个类 User 有(字符串 FirstName,列出兄弟姐妹) 我想修改用户的属性。

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

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

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

用户:{ 名字:“Rbger”, 兄弟姐妹 : { “斯特布林”, “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)
   }
}

上面的代码在修改名字时可以正常工作。但不知道如何修改兄弟姐妹中的字符串。

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

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

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

【问题讨论】:

    标签: c# string list reflection


    【解决方案1】:

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

    例如

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

    以上示例假设兄弟姐妹的propertyInfo为List&lt;string&gt;类型,您可以根据需要进行调整。

    【讨论】:

    • 我可以有一个动态类型。说 propertyInfo.GetValue(t,null) 可以返回 int 列表或字符串列表或 bool 列表。在那种情况下,我该怎么做呢?
    • @Bala,因为 int、string 和 bool 彼此不兼容,您可能没有共同的逻辑来处理所有这些。您可以检查属性类型并有条件地执行代码。见PropertyInfo.PropertyType
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多