简体   繁体   English

在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. 如果我查询数据库然后处理结果,我宁愿创建一个匿名类型并使用它,而不是声明一个永远不会在我的方法范围之外使用或得知的全新类型。

For instance: 例如:

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. 没有人关心`a,匿名类型。 It's there so you don't have to declare another class. 它在那里,所以您不必声明另一个类。

From LINQ in action (page 76 section 2.6.3): 从运行中的LINQ(第76页的2.6.3节):

... anonymous types [are] a great tool for quick and simple temporary results. ...匿名类型是一种快速简便的临时结果的好工具。 We don't need to declare classes to hold temporary results thanks to temporary types. 由于临时类型,我们不需要声明类来保存临时结果。

basically they're useful to hold information in the local scope temporarily. 基本上,它们对于暂时在本地范围内保存信息很有用。 Anything more requires the use of reflection and can become quite a problem. 还有更多需要使用反射的问题,并且可能会成为一个很大的问题。 The example they give in the above-quoted book is in writing to console the id, name, and amount of memory taken up by each running process. 他们在上面引用的书中给出的示例是以书面形式编写的,用于控制台id,名称和每个正在运行的进程占用的内存量。 They create an anonymous type, add it to a list (all one statement) and then use ObjectDumper to output it. 他们创建一个匿名类型,将其添加到列表(所有一条语句)中,然后使用ObjectDumper进行输出。 Therefore the code no longer needs a separately declared class to hold the id, name and memory used but its all declared implicitly bringing the line count down to 4: 因此,代码不再需要单独声明的类来保存所使用的id,名称和内存,而是全部隐式声明,使行数减少到4:

var pl = new List<Object>();
foreach(var p in Process.GetProcesses())
  pl.Add(new {p.Id, p.ProcessName, Memory=p.WorkingSet64});
ObjectDumper.Write(pl);

The most popular use of anonymous types are for specifying projections in a LINQ to SQL query. 匿名类型最流行的用途是在LINQ to SQL查询中指定投影。

This query 这个查询

from x in db.Table1 select new {x.Column1, Alias2=x.Column2}

will be converted to this SQL: 将转换为以下SQL:

SELECT Column1, Column2 AS Alias2 FROM Table1

With anonymous types, you can create ad hoc projections without defining the type for it beforehand. 使用匿名类型,您可以创建临时投影而无需事先为其定义类型。 The compiler will define the type for you. 编译器将为您定义类型。

When you create types for 'Use and throw' purposes. 为“使用和抛出”目的创建类型时。 This seems to have come due to LINQ. 这似乎是由于LINQ造成的。 Seems to be a way to create structures with fields on the fly for a LINQ query. 似乎是一种动态创建具有LINQ查询字段的结构的方法。 Returning a struct/type with specified fields only. 仅返回具有指定字段的结构/类型。 If not for this, you'd have to declare a .Net type for each unique combination of fields you wish to retrieve. 如果不是这样,则必须为每个要检索的字段的唯一组合声明一个.Net类型。

与Linq一起使用。

It is important to know, that LINQ doesn't force you, to use anonymous types. 重要的是要知道,LINQ不会强迫您使用匿名类型。 You can also write normal object constructions after select. 选择后还可以编写普通的对象构造。

var query = from item in database.Items
// ...
select new Person(item.id, item.Name)

This prevents you from ugly reflection programming. 这可以防止您进行丑陋的反射编程。

@Wouter : @Wouter:

var query = from item in database.Items
select new Person
{
ID =item.id,
NAME= item.Name
};

where ID and NAME are real property of your Person class. 其中ID和NAME是您的Person类的不动产。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM