Anonymous Types

前端 未结 5 888
北恋
北恋 2021-01-12 17:41

I have a Dictionary(TKey, TValue) like

Dictionary Deduction_Employees = 
    new Dictionary();

5条回答
  •  轮回少年
    2021-01-12 18:17

    First, you aren't unboxing the type. Anonymous types are reference types, not structures.

    Even though you can technically create instances of the same type outside of the method they were declared in (as per section 7.5.10.6 of the C# 3.0 Language Specification, which states:

    Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.

    ) you have no way of getting the name of the type, which you need in order to perform the cast from Object back to the type you created. You would have to resort to a cast-by-example solution which is inherently flawed.

    Cast-by-example is flawed because from a design standpoint, every single place you want to access the type outside the function it is declared (and still inside the same module), you have to effectively declare the type all over again.

    It's a duplication of effort that leads to sloppy design and implementation.

    If you are using .NET 4.0, then you could place the object instance in a dynamic variable. However, the major drawback is the lack of compile-time verification of member access. You could easily misspell the name of the member, and then you have a run-time error instead of a compile-time error.

    Ultimately, if you find the need to use an anonymous type outside the method it is declared in, then the only good solution is to create a concrete type and substitute the anonymous type for the concrete type.

提交回复
热议问题