我正在尝试编写一个用于排序的通用对象比较器,但我注意到它不处理它比较的值之一为空的实例。当一个对象为空时,我希望它像空字符串一样对待它。我尝试将 null 值设置为 String.Empty,但是在调用 CompareTo() 时出现“对象必须是字符串类型”的错误。
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);
}
我现在很坚持这个!任何帮助,将不胜感激。