应该如何匿名类型在C#中使用? [英] How should anonymous types be used in C#?
问题描述
我见过很多描述匿名类型是如何工作的,但我不知道他们怎么是真正有用的。什么是匿名类型可用于在一个精心设计的方案,以解决一些场景?
I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
推荐答案
匿名类型无关,甚至与在类级别的系统或设计。他们是为开发者编码时使用的工具。
Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding.
我不甚至把匿名类型为每本身的类型。我使用它们主要是作为方法级别匿名的元组。如果我查询数据库,然后操纵的结果,我宁愿创建一个匿名类型和使用,而不是宣布了一个全新的类型,将永远不会被使用或已知我的方法的范围之外。
I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method.
例如:
var query = from item in database.Items
// ...
select new { Id = item.Id, Name = item.Name };
return query.ToDictionary(item => item.Id, item => item.Name);
无人问津`一,匿名类型。它的存在,所以你不必声明另一个类。
Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.
这篇关于应该如何匿名类型在C#中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!