Advantages/Disadvantages of different implementations for Comparing Objects

后端 未结 5 585
滥情空心
滥情空心 2021-02-05 09:27

This questions involves 2 different implementations of essentially the same code.

First, using delegate to create a Comparison method that can be used as a parameter whe

5条回答
  •  无人及你
    2021-02-05 10:11

    There really is no advantage to either option in terms of performance. It's really a matter of convenience and code maintainability. Choose the option you prefer. That being said, the methods in question limit your choices slightly.

    You can use the IComparer interface for List.Sort, which would allow you to not duplicate code.

    Unfortunately, BinarySearch does not implement an option using a Comparison, so you cannot use a Comparison delegate for that method (at least not directly).

    If you really wanted to use Comparison for both, you could make a generic IComparer implementation that took a Comparison delegate in its constructor, and implemented IComparer.

    public class ComparisonComparer : IComparer
    {
        private Comparison method;
        public ComparisonComparer(Comparison comparison)
        {
           this.method = comparison;
        }
    
        public int Compare(T arg1, T arg2)
        {
            return method(arg1, arg2);
        }
    }
    

提交回复
热议问题