将属性添加到ExpandoObject中,其名称与字符串相同 [英] Add property to ExpandoObject with the same name as a string

查看:140
本文介绍了将属性添加到ExpandoObject中,其名称与字符串相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将属性添加到与字符串值同名的ExpandoObject中?

Is there a way to add a property to an ExpandoObject with the same name as a string value?

例如,如果我有:

string propName = "ProductNumber";
dynamic obj = new System.Dynamic.ExpandoObject();

我可以创建属性ProductNumber,例如:

I can create the property ProductNumber like:

obj.ProductNumber = 123;

但是,我可以基于字符串propName创建属性obj.ProductNumber吗?因此,如果我不知道该属性的高级名称,则可以基于此输入来创建它.如果ExpandoObject无法做到这一点,我应该研究C#的其他任何领域吗?

But, can I create the property obj.ProductNumber based on the string propName? So, if I don't know what the name of the property will be in advanced, I can create it based on this input. If this is not possible with ExpandoObject, any other areas of C# I should look into?

推荐答案

ExpandoObject实现IDictionary<string, object>:

ExpandoObject implements IDictionary<string, object>:

((IDictionary<string, object>)obj)[propName] = propValue

我不知道您是否可以在dynamic引用中使用索引器语法(即,不使用强制转换),但是您当然可以尝试并找出来.

I don't know off the top of my head whether you can use the indexer syntax with a dynamic reference (i.e., without the cast), but you can certainly try it and find out.

这篇关于将属性添加到ExpandoObject中,其名称与字符串相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆