Anonymous IComparer implementation

前端 未结 8 1055
一整个雨季
一整个雨季 2021-02-03 17:57

Is it possible to define an anonymous implementation of IComparer?

I believe Java allows anonymous classes to be defined inline - does C#?

Looking at this code I

8条回答
  •  自闭症患者
    2021-02-03 18:21

    As indicated in one of the comments below, .Net 4.5 allows this via a static method on the Comparer<> class, e.g. comparing two objects based on the value of a property in the class:

    var comparer = Comparer.Create( 
            (k1, k2) => k1.Kilowatt.CompareTo(k2.Kilowatt) );
    

    Obviously this can be used inline rather than assigned to a variable.

提交回复
热议问题