我怎样才能让我的通用比较器(IComparer的)处理空值? [英] How can I make my generic comparer (IComparer) handle nulls?
问题描述
我想编写一个通用的对象比较器进行排序,但我已经注意到它不处理的实例,其中它的比较值之一为null。当一个对象是空的,我希望它把它等同于空字符串。我试着设置空值的String.Empty但后来我得到了一个错误对象的类型必须为字符串就可以调用的CompareTo()的时候。
I'm trying to write a generic object comparer for sorting, but I have noticed it does not handle the instance where one of the values it's comparing is null. When an object is null, I want it to treat it the same as the empty string. I've tried setting the null values to String.Empty but then I get an error of "Object must be of type String" when calling CompareTo() on it.
public int Compare(T x, T y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(sortExpression);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (obj1 == null) obj1 = String.Empty; // This doesn't work!
if (obj2 == null) obj2 = String.Empty; // This doesn't work!
if (SortDirection == SortDirection.Ascending)
return obj1.CompareTo(obj2);
else
return obj2.CompareTo(obj1);
}
我是pretty的坚持与此吧!任何帮助将是AP preciated。
I'm pretty stuck with this now! Any help would be appreciated.
推荐答案
您不能把你的 T
为空字符串,除非你的T被有效约束是一个字符串。你的应该采取什么的做的是比较空的计划。如
You cannot treat your T
as an empty string unless your T was effectively constrained to being a string. What you should do is have a plan for comparing nulls. Such as
if (obj1 == null && obj2 == null)
return 0;
else if (obj1 == null)
return -1;
else if (obj2 == null)
return 1;
else
return obj1.CompareTo(obj2);
这篇关于我怎样才能让我的通用比较器(IComparer的)处理空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!