需要超负荷运营商的LT;与空检查 [英] needs overload operator< and null check

查看:84
本文介绍了需要超负荷运营商的LT;与空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm重载每种不超过运营商在C#和我真的不知道这是否需要检查空。下面你可以找到一个例子:

I´m overloading the lessthan-operator in c# and I`m wondering whether this needs to check for null. Below you can find an Example:

public static bool operator <(MyClass x, MyClass y)
{
  if (x == null && y == null)
  {
    return false;
  }
  if (x == null)
  {
    return true; //false?
  }
  if (y == null)
  {
    return false; //true?
  }
  return x.Value < y.Value;
}



或者,这是正确的:

Or is this correct:

public static bool operator <(MyClass x, MyClass y)
{
  return x.Value < y.Value;
}



我didn't找到关于此的任何指令。但是,也许我错过了什么。

I didn´t find any instruction on this. But maybe I missed something.

推荐答案

问题的答案取决于你打算使用模式。如果您计划在空组合,愿与您考虑值小于非空值,那么你的实现是正确的;如果您想考虑值比非空对象时,则注释掉返回值(真正)应改为使用。如果你不打算允许空值的组合,抛出一个 ArgumentNullException 或允许的NullReferenceException 将是正确的选择。

The answer depends on your intended usage pattern. If you plan to have nulls in the mix, and you would like to consider null values to be less than non-null values, then your implementation is correct; if you would like to consider null values to be greater than non-null objects, then the commented out return values (false and true) should be used instead. If you do not plan to allow nulls in the mix, throwing an ArgumentNullException or allowing NullReferenceException would be the right choice.

这篇关于需要超负荷运营商的LT;与空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆