我正在尝试对动态对象的 Observable 集合进行排序。我尝试实现 IComparer,但它告诉我无法实现动态接口(interface)。我现在卡住了。有什么想法可以实现吗?
我试过了
list.OrderByDescending(x => x, new DynamicSerializableComparer());
然后是 IComparer
public class DynamicSerializableComparer : IComparer<dynamic>
{
string _property;
public DynamicSerializableComparer(string property)
{
_property = property;
}
public int Compare(dynamic stringA, dynamic stringB)
{
string valueA = stringA.GetType().GetProperty(_property).GetValue();
string valueB = stringB.GetType().GetProperty(_property).GetValue();
return String.Compare(valueA, valueB);
}
}
最佳答案
IComparer<dynamic>
在编译时与 IComparer<object>
相同. That's why you can't implement it.
尝试实现 IComparer<object>
相反,并转换为动态。
public class DynamicSerializableComparer : IComparer<object>
{
string _property;
public DynamicSerializableComparer(string property)
{
_property = property;
}
public int Compare(object stringA, object stringB)
{
string valueA = stringA.GetType().GetProperty(_property).GetValue();
string valueB = stringB.GetType().GetProperty(_property).GetValue();
return String.Compare(valueA, valueB);
}
}
关于c# - OrderBy、ObservableCollection<动态>、ICompare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7653969/