0
说,我有一个类的用户有(字符串名字,列表兄弟) 我想修改用户的属性。使用反射修改字符串列表
我们假设我想用b替换字符串而不是a。
用户:{ 姓:“狂怒”, 兄弟姐妹:{ “斯大林”, “马克思” }}
使用反射我需要读取各个串和以下将是输出目的。
用户:{ 姓: “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。但不知道如何修改兄弟姐妹中的字符串。
我想我会利用第三个属性(索引属性的可选索引值)。但它看起来像整个财产没有索引。 为同胞,propertyInfo.GetValue(t,null)给出2个字符串。
[0] -- stalin
[1] -- Marx.
谁能告诉我怎么可以让使用propertyInfo.GetValue后的值修改上面的2串(T,NULL)?
我可以有一个动态类型。说propertyInfo.GetValue(t,null)可以返回一个int列表或者字符串列表或者bool列表。在那种情况下,我该怎么做呢? – Bala 2014-12-02 05:09:10
@Bala,因为int,string和bool不相互兼容,你可能没有共同的逻辑来处理它们。您可以检查属性类型并有条件地执行代码。请参阅[PropertyInfo.PropertyType](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.propertytype(v = vs.110).aspx) – pushpraj 2014-12-02 09:13:33
感谢Pushpraj,它的工作。 – Bala 2014-12-15 07:08:38