我知道我可以使用反射来设置如下所示的对象属性。
public void SaveContent(string propertyName, string contentToUpdate, string corePageId)
{
var page = Session.Load<CorePage>(corePageId);
Type type = page.GetType();
PropertyInfo prop = type.GetProperty(propertyName);
prop.SetValue(page, contentToUpdate, null);
}
我在下面上这些课:
public class CorePage
{
public string BigHeader { get; set; }
public List<BigLinks> BigLinks { get; set; }
}
public class BigLinks
{
public string TextContent { get; set; }
}
我的 SaveContent()
-当要设置的属性是例如 public string BigHeader { get; set; }
时,方法显然有效
但是,如果我要设置的属性在属性中,我该怎么做:
public List<BigLinks> BigLinks { get; set; }
如果public List<BigLinks> BigLinks { get; set; }
是 5 BigLinks
的列表对象,如何设置值,例如第三个对象 public string TextContent { get; set; }
?
最佳答案
您必须使用反射获取属性值并像这样更改所需的值:
var c = new CorePage() { BigLinks = new List<BigLinks> { new BigLinks { TextContent = "Y"}}};
var r = typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as List<BigLinks>;
r[0].TextContent = "X";
如果您不知道列表项的类型:
var itemInList = (typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as IList)[0];
itemInList.GetType().GetProperty("TextContent").SetValue(itemInList, "XXX", null);
另一种选择是动态转换:
var itemInList = (typeof(CorePage).GetProperty("BigLinks").GetGetMethod().Invoke(c, null) as dynamic)[0].TextContent = "XXXTTT";
关于c# - Reflections - 当属性在 List<> 中时设置对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25731885/