Return/consume dynamic anonymous type across assembly boundaries

后端 未结 5 836
北海茫月
北海茫月 2020-11-29 08:15

The code below works great. If the Get and Use methods are in different assemblies, the code fails with a RuntimeBinderException. This is because t

5条回答
  •  孤城傲影
    2020-11-29 08:50

    Use an ExpandoObject instead of an anonymous type. This should allow you to cross assembly boundaries safely:

    public static dynamic GetPerson()
    {
        dynamic person = new ExpandoObject();
        person.Name = "Foo";
        person.Age = 30;
    
        return person;
    }
    

    In general, anonymous types should really only be used within the same method in which they are generated. Returning an anonymous type from a method is, in general, going to cause more problems than it solves.

提交回复
热议问题