Why should anonymous types cannot be passed around methods?

后端 未结 6 558
长情又很酷
长情又很酷 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 04:57

    How can you use your type inside your method if the definition is only in the call of the method ?

    It's not javascript.

    0 讨论(0)
  • 2021-01-22 05:03

    At least up to 3.5, anonymous types are actually resolved at compile time, and this would be impossible (or quite hard) to do with anonymous method signatures.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-22 05:11

    Because an anonymous type has no name. Therefore you cannot declare a return type for a method.

    0 讨论(0)
  • 2021-01-22 05:16

    Because C# is statically typed language and in a statically typed language the return type of a method needs to be known at compile time and anonymous types have no names.

    0 讨论(0)
  • 2021-01-22 05:18

    A lot of answers heere seem to indicatie that it is not possible because of the current syntax and rule. But the question is about changing them. I think it would be possible, but a little complicated and resulting in an awkward (error-prone) syntax. Like

    var f() { return new { A = "*", B = 1 }; }
    
    var x = f();
    

    The question is whether this adds sufficient value to the language to make it worth it.

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