简体   繁体   English

在 C# 中,如何从 ExpandoObject 中删除属性?

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

Say I have this object:说我有这个对象:

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

How would I remove foo.bang for example?例如,我将如何删除foo.bang

I don't want to simply set the property's value to null--for my purposes I need to remove it altogether.我不想简单地将属性的值设置为 null——出于我的目的,我需要完全删除它。 Also, I realize that I could create a whole new ExpandoObject by drawing kv pairs from the first, but that would be pretty inefficient.此外,我意识到我可以通过从第一个开始绘制 kv 对来创建一个全新的 ExpandoObject,但这会非常低效。

Cast the expando to IDictionary<string, object> and call Remove :将 expando 转换为IDictionary<string, object>并调用Remove

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

You can treat the ExpandoObject as an IDictionary<string, object> instead, and then remove it that way:您可以将ExpandoObject视为IDictionary<string, object> ,然后以这种方式将其删除:

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

MSDN Example: MSDN 示例:

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

You can cast it as an IDictionary<string,object> , and then use the explicit Remove method.您可以将其转换为IDictionary<string,object> ,然后使用显式Remove方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM