首页 > 解决方案 > C#:如何在动态对象内部的数组中设置项的值?

问题描述

object result = new
{
    items = new[] {
        new {name = "command" , index = "X", optional = "0"},
        new {name = "command" , index = "X", optional = "0"}
    }
};

我想将第一项的名称属性值从“命令”更改为“XYZ”。

以下不起作用。什么是正确的方法?

result.GetType().GetProperties()[0].GetType().GetProperty("Name").SetValue(result,"XYZ")

错误:

System.ArgumentException: 'Property set method not found.'

标签: c#.netasp.net-coreobject

解决方案


简短的回答是匿名类型属性是只读的,不能设置。但是,您可以将其转换Anonymous typesExpandoObject

自定义ToExpando方法:

public static class Extension
{
    public static IEnumerable<dynamic> ToExpando(this IEnumerable<object> anonymousObject)
    {
        IList<dynamic> list = new List<dynamic>();

        foreach (var item in anonymousObject)
        {
            IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(item);
            IDictionary<string, object> expando = new ExpandoObject();

            foreach (var nestedItem in anonymousDictionary)
                expando.Add(nestedItem);

            list.Add(expando);
        }

        return list.AsEnumerable();
    }
}

修改匿名类型值:

//change object to var...
var result = new
{
    items = new[] {
        new {name = "command" , index = "X", optional = "0"},
        new {name = "command" , index = "X", optional = "0"}
    }
};
var data = result.items.ToExpando().ToList();

//modify the value of name property
data.First().name = "XYZ";

推荐阅读