字符串的自定义比较器是否应该允许空值
我正在查看其他人的用于比较字符串的自定义比较器的代码。
我注意到,如果至少一个字符串参数为空,它就会崩溃。
比较根据比较结果返回 -1、0 或 1。
是否应该修复这样的代码来处理空值,如果是的话,如果参数之一为空,它应该返回什么?
I'm looking at someone elses code for a custom comparer that compares strings.
I'm noticing that it will fall over if at least one of the string parameters is null.
The compare returns -1, 0 or 1 based on the result of the comparison.
Should code like this be fixed to handle nulls and if so what should it return if one of the parameters was null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 IComparer.Compare 方法 (MSDN )
即,以下内容似乎是合理的:
According to the remarks section of the IComparer.Compare Method (MSDN)
I.e. the following seems sensible:
答案最终将/应该是您的业务需求的结果。
代码可能是根据一组特定的要求编写的,并且空值不属于考虑范围。
如果出现以下情况,则应修复此问题:
The answer will/should ultimately be a result your business requirements.
Likely the code was written to a certain set of requirements, and nulls weren't part of the consideration.
It should be fixed if:
我想这取决于比较器的目的,但我倾向于更改比较器以在其中一个字符串为空时引发异常。这似乎违背了比较器的目的,即返回一个字符串是否大于、等于或小于另一个字符串。 Null 不适合该集合。
I guess it depends on the purpose of the comparer, but I would lean toward changing the comparer to throw an exception if one of the strings is null. It seems to go against the purpose of the comparer, which is to return whether one string is greater than, equal to, or lesser than the other string. Null doesn't fit into that set.