Can I specify a meaningful name for an anonymous class in C#?

后端 未结 10 1744
小蘑菇
小蘑菇 2021-02-01 13:12

We all know that when we create an anonymous class like this:

var Employee = new { ID = 5, Name= \"Prashant\" };

...at run time it will be of t

相关标签:
10条回答
  • 2021-02-01 14:13

    Yes, you are creating an Anonymous Class , if you want your class to have a name, i.e. Not Anonymous, then declare a regular class or struct.

    0 讨论(0)
  • 2021-02-01 14:16

    The answer in Java World would be a local class (defined in a method), which are absent in C#.

    0 讨论(0)
  • 2021-02-01 14:17

    No, there is no way to give a meaningful type name to these classes as you've declared them. Anonymous Types are just that, anonymous. There is no way to explicitly "name" the type in code without resorting to very ugly hacks.

    If you really need to give the type a name you will need to explicitly declare and use a new type with the properties you need.

    0 讨论(0)
  • 2021-02-01 14:17

    I think that, by definition, Anonymous Types can't have a name, just that which the compiler gives it. If you're looking for more meaningful design-time information on Anonymous Types then you're expecting too much from the compiler.

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