如何使我的通用比较器 (IComparer) 处理空值?
我正在尝试编写一个用于排序的通用对象比较器,但我注意到它不能处理它所比较的值之一为空的实例。当一个对象为空时,我希望它像空字符串一样对待它。我尝试将 null 值设置为 String.Empty 但在调用 CompareTo() 时出现“对象必须是 String 类型”错误。
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);
}
我现在很纠结这个!任何帮助将不胜感激。
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);
}
I'm pretty stuck with this now! Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除非您的 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由于
T
是泛型类型,因此您不能为其分配String
值;您只能为其分配T
类型的值。如果您只想用它来比较字符串,请使用String
而不是T
。否则,添加 null 检查并决定null
应该落在哪里。Since
T
is a generic type, you cannot assign it aString
value; you can only assign it a value of typeT
. If you are only going to use this to compare strings, useString
instead ofT
. Otherwise, add null checking and decide where in ordernull
should fall.这基本上意味着 obj1 现在将是 propertyInfo.GetValue(x, null) 的值,或者,如果恰好为 null,则 obj1 将是“”。
或者,如果问题是 GetValue 在 null 上崩溃,您可以执行以下操作:
This basically means that obj1 will now be the value of propertyInfo.GetValue(x, null) or, if that happens to be null, obj1 will be "".
Or if the problem is that the GetValue crashes on null you could do something like: