ExpandoObject便利工厂?

时间:2016-04-26 11:01:18

标签: c# expandoobject

ExpandoObject是否有任何便利工厂方法?有点像,我不知道,

dynamic disney = new ExpandoObject("First", "Donald", "Last", "Duck");

1 个答案:

答案 0 :(得分:5)

不,没有,但你可以在几分钟内写出来。 :) 你走了:

C#

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = ExpandoFactory.Create("First", "Donald", "Last", "Duck");
        Console.WriteLine(ex.First);
        Console.WriteLine(ex.Last);
    }
}

static class ExpandoFactory
{
    internal static ExpandoObject Create(params string[] items)
    {
        //safety checks omitted for brevity
        IDictionary<string, object> result = new ExpandoObject();
        for (int i = 0; i < items.Length; i+=2)
        {
            result[items[i]] = items[i + 1];
        }
        return result as ExpandoObject;
    }
}

当然,您应该事先检查阵列的基数。 我希望这会有所帮助。