How can I use collection initializer syntax with ExpandoObject?

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

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

6条回答
  •  攒了一身酷
    2021-02-07 08:58

    First of all, you are spot on. The IDictionary has been implemented explicitly.

    You do not even need casting. This works:

    IDictionary exdict = new ExpandoObject() 
    

    Now the reason collection syntax does not work is because that is an implementation in the Dictionary constructor and not part of the interface hence it will not work for expando.

    Wrong statement above. You are right, it uses add function:

    static void Main(string[] args)
    {
    Dictionary dictionary = new Dictionary()
                                                    {
                                                        {"Ali", "Ostad"}
                                                    };
    }
    

    Gets compiled to

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       27 (0x1b)
      .maxstack  3
      .locals init ([0] class [mscorlib]System.Collections.Generic.Dictionary`2 dictionary,
               [1] class [mscorlib]System.Collections.Generic.Dictionary`2 '<>g__initLocal0')
      IL_0000:  nop
      IL_0001:  newobj     instance void class [mscorlib]System.Collections.Generic.Dictionary`2::.ctor()
      IL_0006:  stloc.1
      IL_0007:  ldloc.1
      IL_0008:  ldstr      "Ali"
      IL_000d:  ldstr      "Ostad"
      IL_0012:  callvirt   instance void class [mscorlib]System.Collections.Generic.Dictionary`2::Add(!0,
                                                                                                                     !1)
      IL_0017:  nop
      IL_0018:  ldloc.1
      IL_0019:  stloc.0
      IL_001a:  ret
    } // end of method Program::Main
    

    UPDATE

    The main reason is Add has been implemented as protected (with no modifier which becomes protected).

    Since Add is not visible on ExpandoObject, it cannot be called as above.

提交回复
热议问题