dynamic item = new { code = "111", name = "大熊" };
如上直接定义了,不遍历的情况下怎么去修改name属性值
这个是 anonymous object,无法实现。
如果能换成 ExpandoObject,就不费吹灰之力
using System.Dynamic;
dynamic item = new ExpandoObject();
item.code = "111";
item.name = "大熊";
item.name = "小熊";
Console.WriteLine(item.name);
dynamic item = new { code = "111", name = "大熊" };
有方法能将上面的直接转成ExpandoObject吗
@菜菜灰: 要用反射
顺便问一下,new ExpandoObject() 有集合初始化器方法吗
@菜菜灰: 需要借助 Dictionary,参考 https://stackoverflow.com/a/43411810/5989202 的实现代码
using System.Dynamic;
IDictionary<string, object> dict = new Dictionary<string, object>()
{
{ "code", "111"},
{ "name", "大熊"},
};
dynamic item = dict.Aggregate(
new ExpandoObject() as IDictionary<string, object>,
(a, p) => { a.Add(p); return a; });
Console.WriteLine(item.name);
item.name = "小熊";
Console.WriteLine(item.code);
Console.WriteLine(item.name);