to sort a collection that I do not know what type does it have?
Is there a way in .NET that I can sort my collection when I do not know what types of objects at run time I will pass to this collection and also by avoiding Reflec开发者_如何学Ction.
any thoughts?
You do need some way of comparing elements. The usual way is to demand IComparable:
class MyCollection<T> where T : IComparable<T>
{
}
or use an IComparer, either for the Sorting method or the constructor:
class MyCollection<T> // where T : IComparable<T>
{
void Sort(IComparer<T> comparer)
{
if (comparer.Compare(a, b) > 0) { ... }
}
}
Why can't you use an ArrayList
collection?
ArrayList list = new ArrayList();
list.Add("R");
list.Add("B");
list.Add("G");
list.Sort();
//produces "B","G","R"
list.Clear();
list.Add(100);
list.Add(10);
list.Add(9);
list.Sort();
//produces 9,10,100
精彩评论