In C#, how do I remove a property from an ExpandoObject?

半腔热情 提交于 2020-01-03 07:09:24

问题


Say I have this object:

dynamic foo = new ExpandoObject();
foo.bar = "fizz";
foo.bang = "buzz";

How would I remove foo.bang for example?

I don't want to simply set the property's value to null--for my purposes I need to remove it altogether. Also, I realize that I could create a whole new ExpandoObject by drawing kv pairs from the first, but that would be pretty inefficient.


回答1:


Cast the expando to IDictionary<string, object> and call Remove:

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");



回答2:


You can treat the ExpandoObject as an IDictionary<string, object> instead, and then remove it that way:

IDictionary<string, object> map = foo;
map.Remove("Jar");



回答3:


MSDN Example:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");



回答4:


You can cast it as an IDictionary<string,object>, and then use the explicit Remove method.

IDictionary<string,object> temp = foo;
temp.Remove("bang");


来源:https://stackoverflow.com/questions/13567663/dynamically-removing-a-member-from-expando-dynamic-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!