Dictionary with Func as key

前端 未结 3 988
失恋的感觉
失恋的感觉 2020-12-31 12:50

I am wondering if this is a sane choice of key for a dictionary? What I want to do is use an expression as the key in a dictionary, something like:

    var m         


        
3条回答
  •  -上瘾入骨i
    2020-12-31 13:14

    No, C# constructs a new delegate instance whenever a lambda is used so you wouldn't be able to use it as a consistent key. Example:

            Func f = x => x*x + 1;
            Func g = x => x*x + 1;
            Console.WriteLine(f.Equals(g)); // prints False
    

    This would then make usage awkward as a dictionary key unless you had some other way to always obtain the same instance.

    Edit:

    Eric Lippert's answer here indicates that the compiler is allowed to detect the lambdas are the same (although it typically does not). Either way a lambda/delegate makes a poor choice for a key.

提交回复
热议问题