Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?

前端 未结 2 1694
耶瑟儿~
耶瑟儿~ 2020-12-28 13:31

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

internal static class PlayCardActionValidator
{
    public static bool CanPl         


        
2条回答
  •  没有蜡笔的小新
    2020-12-28 14:31

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

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

    Other posters already explained the why part, so the better question would be How can I avoid creation of a closure?. And the answer is simple: if lambda is using only the passed parameters and/or constants, the compiler will not create a closure. For instance:

    bool AnyClub() { return playerCards.Any(c => c.Suit == CardSuit.Club); }
    
    bool AnyOf(CardSuit suit) { return playerCards.Any(c => c.Suit == suit); }
    

    The first will not create a closure while the second will.

    With all that in mind, and assuming you don't want to use for/foreach loops, you can create own extension methods similar to those in System.Linq.Enumerable but with additional parameters. For this particular case, something like this would work:

    public static class Extensions
    {
        public static bool Any(this IEnumerable source, TArg arg, Func predicate)
        {
            foreach (var item in source)
                if (predicate(item, arg)) return true;
            return false;
        }
    } 
    

    and change the code in question to:

    var hasBigger =
        playerCards.Any(otherPlayerCard, 
            (c, opc) => c.Suit == opc.Suit
                 && c.GetValue() > opc.GetValue());
    

提交回复
热议问题