【问题标题】:Reflections -Set objects property when the property is in a List<>反射 - 当属性位于 List<> 中时设置对象属性
【发布时间】:2014-11-02 02:57:01
【问题描述】:

我知道我可以使用反射来设置对象属性,如下所示。

    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; }
}

当要设置的属性是 public string BigHeader { get; set; } 时,我的 SaveContent() 方法显然有效 但是如果我要设置的属性在属性中,我该怎么做:

public List<BigLinks> BigLinks { get; set; }

如果public List&lt;BigLinks&gt; BigLinks { get; set; } 是5 个BigLinks 对象的列表,如何设置例如第三个对象public string TextContent { get; set; } 的值?

【问题讨论】:

标签: c# system.reflection


【解决方案1】:

您必须使用反射获取属性值并像这样更改所需的值:

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";

【讨论】:

  • 没有演员表我可以这样做吗:as List&lt;BigLinks&gt;;?我需要以更动态的方式拥有它,因为List&lt;&gt; 并不总是List&lt;BigLinks&gt; 而且我不想为每个可能的列表都有一个方法
  • 你想如何使用它?通常让所有用于代替 BigLink 的类都实现一个通用接口(如 IBigLink)并在您的 CorePage 中使用 List 而不是 List
  • 转换回类型违背了使用反射的目的。如果他知道将其转换为什么类型,他就不会使用反射。
  • @brz 我的意思是要投射的列表可以是任何其他列表。 CorePage 类也有其他列表,例如:public List&lt;AnotherList&gt; AnotherList { get; set; } 然后我必须像那样投射它,这意味着我需要为任何可能的列表进行投射。只是在想它可以以更动态的方式完成
猜你喜欢
  • 2010-10-11
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多