How do I access an anonymous object's properties outside its scope?

前端 未结 4 968
终归单人心
终归单人心 2021-01-25 19:08

Scope might not be the right word. With the following code I can\'t get access to the collections element\'s object\'s properties. Is there a better return data type or a way t

相关标签:
4条回答
  • 2021-01-25 19:39

    Once you leave the scope in which the anonymous type was defined, you have to use reflection to get to its members.

    The two other options I can think of are to use a dynamic type (if using 4.0 framework or later) or to create a defined type instead of an anonymous type.

    0 讨论(0)
  • 2021-01-25 19:42

    There are two feasible solutions:

    1. Create a real class for it. That's the prefered solution.
    2. Make your method return dynamic instead of object. The problem with this is that you lose compile time checking of the code that uses the result of this method.
    0 讨论(0)
  • 2021-01-25 19:45

    Use IEnumerable<dynamic> instead.

    According to msdn "The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM)."

    http://msdn.microsoft.com/en-us/library/dd264741.aspx

    0 讨论(0)
  • 2021-01-25 20:01

    I would recommend simply creating a new type for passing the data. If the scope of the data is protected, you can used a protected nested subclass to prevent over-proliferation of small data classes.

    0 讨论(0)
提交回复
热议问题