Implementing IComparer<T> For IComparer<DictionaryEntry>
I am using the ObservableSortedDictionary from Dr. WPF.
The constructor looks like this:
public ObservableSortedDictionary(IComparer<DictionaryEntry> comparer)
I am really struggling to create an implementation that satisfies the constructor and works.
My current code (that won't compile) is:
public class TimeCreatedComparer<T> : IComparer<T>
{
public int Compare(T x, T y)
{
var myclass1 = (IMyClass)((DictionaryEntry)x).Value;
var myclass2 = (IMyClass)((DictionaryEntry)y).Value;
开发者_运维问答 return myclass1.TimeCreated.CompareTo(myclass2.TimeCreated);
}
}
It says I can't cast from T to DictionaryEntry.
If I cast directly to IMyClass, it compiles, but I get a runtime error saying I can't cast from DictionaryEntry to IMyClass. At runtime, x and y are instances of DictionaryEntry, which each have the correct IMyClass as their Value.
public class TimeCreatedComparer : IComparer<DictionaryEntry>
{
public int Compare(DictionaryEntry x, DictionaryEntry y)
{
var myclass1 = (IMyClass)x.Value;
var myclass2 = (IMyClass)y.Value;
return myclass1.TimeCreated.CompareTo(myclass2.TimeCreated);
}
}
Does this do what's needed?
精彩评论