为什么匿名类型不能在方法周围传递?[英] Why should anonymous types cannot be passed around methods?

本文是小编为大家收集整理的关于为什么匿名类型不能在方法周围传递?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

倾向于不从方法返回匿名类型的设计决定是什么?

推荐答案

you can 从方法返回匿名类型的实例 - 但是由于您无法命名,您无法确切声明该方法将返回的内容,因此您' D必须声明它仅返回object.这意味着呼叫者将无法静态键入对属性等的访问 - 尽管它们仍然可以通过实例,但通过反射访问(或在C#4中的动态键入).

我个人非常希望C#的未来版本允许您编写一个非常简短的类声明,该声明生成了一个名称...

有一个一个 grotty hack可以围绕它,称为按示例铸造.我不推荐.

其他推荐答案

因为匿名类型没有名称.因此,您不能声明方法的返回类型.

其他推荐答案

因为C#是静态键入的语言,在静态键入语言中,方法的返回类型需要在编译时知道,并且匿名类型没有名称.

本文地址:https://www.itbaoku.cn/post/627319.html

问题描述

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

推荐答案

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.

其他推荐答案

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

其他推荐答案

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.