c# - 如果匿名类型应该是不可变的,为什么可以更改它?

标签 c# linq

我以为我对匿名类型有很好的理解,但是这个小代码片段让我有点困惑:

string[] arr = { "Agnes", "Allan", "Benny" };

var result = arr.Where(a => a.StartsWith("A")).Select(a => a);

// Why can I do the below, if arr is immutable?
result = arr.Where(a => a.EndsWith("n")).Select(a => a);

我不明白的是为什么允许我为 result 分配第二个值。我的意思是匿名类型的想法不是不可变的,即它们在获得初始值后就不能更改吗?

最佳答案

首先,没有anonymous type参与。


string[] arr = { "Agnes", "Allan", "Benny" };是一个 array creation expression .

resultIEnumerable<string>在这两个 LINQ 语句中,您只是在创建一个查询。

这是正在发生的事情:

数组创建表达式

string[] arr = { "Agnes", "Allan", "Benny" }; 

查询 arr 并返回 IEnumerable<string>

var result = arr.Where(a => a.StartsWith("A")).Select(a => a); 

为返回 IEnumerable<string> 的 arr 上的新查询分配结果

result = arr.Where(a => a.EndsWith("n")).Select(a => a); 

就理解不变性而言,想想 String另见这篇文章:Immutable types: understand their benefits and use them

关于c# - 如果匿名类型应该是不可变的,为什么可以更改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538766/

相关文章:

c# - 无法将 DBNull.Value 转换为类型 'System.DateTime' 。请使用可空类型。关于使用 Linq 查询

c# - 与 Linq 中的 group by 不同

c# - EF5 和 Lambda/Linq - 如何仅包含相关表的某些列

c# - 未实现 WCF 接口(interface)

c# - 如何传入将用作数据表中行的过滤器的 lambda?

c# - IEnumerable.Select() 可以跳过一个项目吗?

c# - 如何使用c#仅获取文件夹中的最后两个文件

c# - 帮助将小型 C# WCF 应用程序转换为 Visual Basic(第 2 部分)

c# - "Cannot perform ' = ' operation on System.Int32 and System.String"执行搜索时

LINQ - 加入动态查询