c# - Reflections - 当属性在 List<> 中时设置对象属性

标签 c# system.reflection

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

    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/

相关文章:

c# - ASP.NET Core 中的 Cookie 身份验证过期过早

c# - 为什么 `dynamicMethod.CreateDelegate(typeof(Action)).Method.Invoke(null,new object[0]);` 抛出异常?

c# - System.Data.dll 上系统程序集的 .NET 反射失败

c# - 获取 WPF 项目的项目名称

C# 访问所有者对象的自定义属性

c# - 是否可以在已停止的 IIS 6 站点上预编译 ASP.Net 网站?

javascript - 如何通过从 C# 传递多个参数来调用 javascript

c# - 正在分析 FxCop/代码分析警告 CA1506 : AvoidExcessiveClassCoupling

c# - 如何在 SQL Server 中存储 Point 数据类型?

C# 将字符串变量转换为对象类型引用