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

2019-02-04 05:31发布

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.

4条回答
可以哭但决不认输i
2楼-- · 2019-02-04 05:42

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

var dict = (IDictionary<string, object>)foo;
dict.Remove("bang");
查看更多
放荡不羁爱自由
3楼-- · 2019-02-04 05:44

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");
查看更多
The star\"
4楼-- · 2019-02-04 05:48

MSDN Example:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
查看更多
劳资没心,怎么记你
5楼-- · 2019-02-04 05:48

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

IDictionary<string,object> temp = foo;
temp.Remove("bang");
查看更多
登录 后发表回答