如何对ExpandoObject使用集合初始化语法? [英] How can I use collection initializer syntax with ExpandoObject?

查看:926
本文介绍了如何对ExpandoObject使用集合初始化语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,新的 ExpandoObject 实现了 IDictionary< string,object> c $ c> IEnumerable< KeyValuePair< string,object>> 和 Add(string,object)方法,因此应该可以使用

I've noticed that the new ExpandoObject implements IDictionary<string,object> which has the requisite IEnumerable<KeyValuePair<string, object>> and Add(string, object) methods and so it should be possible to use the collection initialiser syntax to add properties to the expando object in the same way as you add items to a dictionary.

Dictionary<string,object> dict = new Dictionary<string,object>() 
{
    { "Hello", "World" }
};

dynamic obj = new ExpandoObject()
{
    { "foo", "hello" },
    { "bar", 42 },
    { "baz", new object() }
};

int value = obj.bar;

但似乎没有办法。错误:

But there doesn't seem to be a way of doing that. Error:


'System.Dynamic.ExpandoObject'不包含'Add'的定义

'System.Dynamic.ExpandoObject' does not contain a definition for 'Add'

我假设这不工作,因为接口是明确实现的。
但是有什么办法解决这个问题吗?这工作正常,

I assume this doesn't work because the interface is implemented explicitly. but is there any way of getting around that? This works fine,

IDictionary<string, object> exdict = new ExpandoObject() as IDictionary<string, object>();
exdict.Add("foo", "hello");
exdict.Add("bar", 42);
exdict.Add("baz", new object());

但是集合初始化语法更简洁。

but the collection initializer syntax is much neater.

推荐答案

我之前需要一个简单的ExpandoObject初始化器,通常使用下面的两个扩展方法来完成类似初始化语法:

I've had the need for a simple ExpandoObject initializer several times before and typically use the following two extension methods to accomplish something like initializer syntax:

public static KeyValuePair<string, object> WithValue(this string key, object value)
{
    return new KeyValuePair<string, object>(key, value);
}

public static ExpandoObject Init(
    this ExpandoObject expando, params KeyValuePair<string, object>[] values)
{
    foreach(KeyValuePair<string, object> kvp in values)
    {
        ((IDictionary<string, Object>)expando)[kvp.Key] = kvp.Value;
    }
    return expando;
}

然后您可以写下:

dynamic foo = new ExpandoObject().Init(
    "A".WithValue(true),
    "B".WithValue("Bar"));

一般来说,我发现有一个扩展方法来构建 KeyValuePair< string,object> 实例从字符串键派上用场。你可以改变名称为 is ,这样你可以写Key.Is(Value)如果你需要更简洁的语法。

In general I've found that having an extension method to build KeyValuePair<string, object> instances from a string key comes in handy. You can obviously change the name to something like Is so that you can write "Key".Is("Value") if you need the syntax to be even more terse.

这篇关于如何对ExpandoObject使用集合初始化语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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