How can I use collection initializer syntax with ExpandoObject?

后端 未结 6 989
温柔的废话
温柔的废话 2021-02-07 08:24

I\'ve noticed that the new ExpandoObject implements IDictionary which has the requisite IEnumerable

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 08:59

    Using the idea from @samedave, and adding reflection, I got this:

    void Main()
    {
        dynamic foo = new ExpandoObject().Init(new
        {
            A = true,
            B = "Bar"
        });
    
        Console.WriteLine(foo.A);
        Console.WriteLine(foo.B);
    }
    
    public static class ExtensionMethods
    {
        public static ExpandoObject Init(this ExpandoObject expando, dynamic obj)
        {
            var expandoDic = (IDictionary)expando;
            foreach (System.Reflection.PropertyInfo fi in obj.GetType().GetProperties())
            {
               expandoDic[fi.Name] = fi.GetValue(obj, null);
            }
            return expando;
        }
    }
    

    But it would be nicer to be able to just do it like:

    dynamic foo = new ExpandoObject
    {
        A = true,
        B = "Bar"
    };
    

    Please vote for this feature in Visual Studio UserVoice.

    Update:

    Using Rick Strahl's Expando implementation you should be able to do something like this:

    dynamic baz = new Expando(new
    {
        A = false,
        B = "Bar2"
    });
    
    Console.WriteLine(baz.A);
    Console.WriteLine(baz.B);
    

提交回复
热议问题