为什么匿名类型不能传递方法?

编程入门 行业动态 更新时间:2024-10-24 01:59:03
本文介绍了为什么匿名类型不能传递方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

解决方案

您可以从方法返回匿名类型的实例 - 但是因为您可以' 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.

更多推荐

为什么匿名类型不能传递方法?

本文发布于:2023-11-09 20:29:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!