c# - 为什么 LINQ 扩展以非常难以阅读的方式编写?

标签 c# .net linq

我正在检查一些在 Reflector 中构成 LINQ 扩展的代码,这是我遇到的那种代码:

private bool MoveNext()
{
    bool flag;
    try
    {
        switch (this.<>1__state)
        {
            case 0:
                this.<>1__state = -1;
                this.<set>5__7b = new Set<TSource>(this.comparer);
                this.<>7__wrap7d = this.source.GetEnumerator();
                this.<>1__state = 1;
                goto Label_0092;

            case 2:
                this.<>1__state = 1;
                goto Label_0092;

            default:
                goto Label_00A5;
        }
    Label_0050:
        this.<element>5__7c = this.<>7__wrap7d.Current;
        if (this.<set>5__7b.Add(this.<element>5__7c))
        {
            this.<>2__current = this.<element>5__7c;
            this.<>1__state = 2;
            return true;
        }
    Label_0092:
        if (this.<>7__wrap7d.MoveNext())
        {
            goto Label_0050;
        }
        this.<>m__Finally7e();
    Label_00A5:
        flag = false;
    }
    fault
    {
        this.System.IDisposable.Dispose();
    }
    return flag;
}

Microsoft 有这样写的理由吗?

还有 <> 语法是什么意思,像这样的行:

switch (this.<>1__state)

我从来没见过它写在变量之前,只有在之后。

最佳答案

MSIL 仍然是有效的 2.x 代码,您看到的 <> 名称是由 C# 3.x 编译器自动生成的。

例如:

public void AttachEvents()
{
    _ctl.Click += (sender,e) => MessageBox.Show( "Hello!" );
}

翻译成类似的东西:

public void AttachEvents()
{
    _ctl.Click += new EventHandler( <>b_1 );
}

private void <>b_1( object sender, EventArgs e )
{
    MessageBox.Show( "Hello!" );
}

我还应该指出,您在 Reflector 中看到它的原因是您没有打开 .NET 3.5 优化。转到查看 |选项并将优化更改为 .NET 3.5,它将更好地将生成的标识符转换回它们的 lamda 表达式。

关于c# - 为什么 LINQ 扩展以非常难以阅读的方式编写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1061013/

相关文章:

c# - 创建两个具有相同友好名称的应用程序域

c# - AES _Encryption 在 Mysql 中,在 C#.Net 中解密

.NET DropDownList SelectedIndexChanged 事件未在 IE 10 中触发

.net - project.json 相当于 InternalsVisibleTo

c# - LINQ 如何获取一条记录并跳过其余的 c#

c# - A-Star (A*) 和通用查找方法

c# - F# 无法发布到 web api?

c# - 按日期排列的列表,将 future 与过去日期分开

c# - 由于极不可能的情况发生而丢失数据包?

c# - 如何使用 LINQ 正确折叠?