为什么匿名类型不能传递方法? [英] Why should anonymous types cannot be passed around methods?
问题描述
倾向于不从方法返回匿名类型的设计决策是什么?
您可以从方法返回匿名类型的实例 - 但是因为您可以' t命名它,你无法声明方法将返回什么,所以你必须声明它只返回对象
。这意味着调用者不会对属性等进行静态类型访问,尽管它们仍然可以传递实例,通过反射访问它(或者在C#4中进行动态输入)。
个人来说,我很喜欢C#的未来版本,允许您编写一个非常简短的类声明,它使用名称生成相同的代码(不可变属性,构造函数,Equals / GetHashcode / ToString)。
有一个一个 grotty黑客去,称为铸造示例。我不会推荐它。
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.
这篇关于为什么匿名类型不能传递方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!