c# - 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.'
解决方案
简短的回答是匿名类型属性是只读的,不能设置。但是,您可以将其转换Anonymous types
为ExpandoObject
:
自定义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";
推荐阅读
- vba - VBA:自定义右键单击菜单选项不可见
- google-cloud-dataflow - JdbcIO 或自定义接收器以使用特定的数据库批量实用程序
- javascript - 停止图像的滚动
- gradle - 添加了凭据,现在找不到参数的方法 pluginRepositories()
- apache - 将子域重写到文件夹后避免内容重复
- sql - 如何在oracle sql中提取特定值
- c# - .NET Web Api 相同的 http 动词,不同的命名方法
- php - 如何在 Laravel 5.6 中使用一个字母正则表达式验证数字?
- excel - 使用 VLOOKUP 和 SUMIF 处理未决交易和已发布交易
- python - Discord bot 添加对消息 discord.py 的反应(无自定义表情符号)