我可以安全地使用DateTime作为SortedDictionary<K, V>中的一个键,而无需实现我自己的IComparer ?
我试过了,排序顺序保持不变,对我的目的来说很重要.ContainsKey<T>方法按预期工作。 但我只是想在这条道路上投入自己之前仔细检查。
Can I safely use DateTime as a key in a SortedDictionary<K, V> without implementing my own IComparer?
I've tried it and sort order is maintained and importantly for my purpose the .ContainsKey<T> method works as expected. But I just want to double check before committing myself down this road.
最满意答案
你将不需要一个新的IComparer。 您的默认IComparer将使用您的值对象中的GetHashCode()并与其进行比较/排序。 由于DateTime类型正确地实现了GetHashCode(),因此默认的IComparer将按照您的需要进行排序(就像您发现的那样)。
创建新的比较器更适合您自己编写的复杂集合。 我写了一次复杂的比较器。 这有点令人兴奋。
you will not need a new IComparer. your default IComparer will use the GetHashCode() from your value object and compare/sort with that. Since the DateTime type implements the GetHashCode() correctly, the default IComparer will sort as you want it to (like you have discovered).
creating new comparer's is more for complex collections that you may have written yourself. i wrote a complex comparer once. it's a bit mind blowing.
更多推荐
发布评论