在使用LINQ方法Any()时,为什么C#编译器会创建私有的DisplayClass,我该如何避免呢? [英] Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?

查看:139
本文介绍了在使用LINQ方法Any()时,为什么C#编译器会创建私有的DisplayClass,我该如何避免呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码(整个代码并不重要,但可以在

I have this code (the whole code is not important but can be seen on this link):

internal static class PlayCardActionValidator
{
    public static bool CanPlayCard(...)
    {
        // ...
        var hasBigger =
            playerCards.Any(
                c => c.Suit == otherPlayerCard.Suit
                     && c.GetValue() > otherPlayerCard.GetValue());
        // ...
    }
}

例如,在反编译器(ILSpy)中打开代码后,我注意到C#编译器存在新创建的类<​​c0>:

After opening the code in decompiler (ILSpy) for example I noticed the existence of newly created class <>c__DisplayClass0_0 by the C# compiler:

如果此代码对系统性能不是关键,那么这对我来说就不是问题.这种方法被称为数百万次,垃圾回收器正在清理以下<>c__DisplayClass0_0实例,这会降低性能:

This wouldn't be a problem for me if this code wasn't critical for the performance of the system. This method is called millions of times and the garbage collector is cleaning these <>c__DisplayClass0_0 instances which slows down the performance:

使用Any方法时如何避免创建此类(他的实例及其垃圾收集)?

How can I avoid creating this class (his instances and their garbage collecting) when using the Any method?

为什么C#编译器会创建此类,并且我可以使用Any()的任何替代方法?

Why does the C# compiler create this class and is there any alternative of Any() I can use?

推荐答案

要了解显示类",您必须了解闭包.您在此处传递的lambda是 closure ,这是一种特殊的方法,可以神奇地将状态从其所在方法的范围内拖入并封闭".

To understand the "display class" you have to understand closures. The lambda you pass here is a closure, a special type of method that magically drags in state from the scope of the method it's in and "closes around" it.

...当然不存在魔术之类的东西.所有这些状态必须实际存在于某个真实的地方,该地方与闭包方法相关联并且可以从中方便地获得.怎样将状态直接与一个或多个方法相关联的编程模式又叫什么?

...except of course that there's no such thing as magic. All that state has to actually live somewhere real, somewhere that's associated with the closure method and readily available from it. And what do you call the programming pattern where you associate state directly with one or more methods?

是的:类.编译器将lambda转换为闭包类,然后实例化托管方法中的类,以便托管方法可以访问该类中的状态.

That's right: classes. The compiler transforms the lambda into a closure class, then instantiates the class inside the hosting method so the hosting method can access the state in the class.

不发生这种情况的唯一方法是不使用闭包.如果这确实影响性能,请使用老式的FOR循环而不是LINQ表达式.

The only way to not have this happen is to not use closures. If this is really impacting performance, use an old-school FOR loop instead of a LINQ expression.

这篇关于在使用LINQ方法Any()时,为什么C#编译器会创建私有的DisplayClass,我该如何避免呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆