Why should anonymous types cannot be passed around methods?

后端 未结 6 560
长情又很酷
长情又很酷 2021-01-22 04:27

What is the design decision to lean towards not returning an anonymous types from a method?

6条回答
  •  被撕碎了的回忆
    2021-01-22 05:08

    You can return an instance of an anonymous type from a method - but because you can't name it, you can't declare exactly what the method will return, so you'd have to declare that it returns just object. That means the caller won't have statically typed access to the properties etc - although they could still pass the instance around, access it via reflection (or dynamic typing in C# 4).

    Personally I would quite like a future version of C# to allow you to write a very brief class declaration which generates the same code (immutable properties, constructor, Equals/GetHashcode/ToString) with a name...

    There is one grotty hack to go round it, called casting by example. I wouldn't recommend it though.

提交回复
热议问题