如何在C#中使用compareTo命令null对象

时间:2016-03-09 12:49:54

标签: null nullreferenceexception compareto

我有一个名为UserView的类,我实现了他的compareTo()方法。

我有这个限制:"如果将UserView与空的UserView进行比较,则null会先于另一个"

我有compareTo():

 public int CompareTo(UserView other)
    {
        if (this == null && other != null) return -1;
        else if (this == null && other == null) return 0;
        else return Id.CompareTo(other.Id);
    }

这个测试:

 [TestMethod]
    public void TestCompareWithNull()
    {
        UserView uv = new UserView(1, "pepe", "1234", "alumno", true);
        UserView uv2 = null;
        UserView uv3 = null;
        Assert.AreEqual(uv2.CompareTo(uv3), 0);
        Assert.AreEqual(uv2.CompareTo(uv), -1);
        Assert.AreEqual(uv.CompareTo(uv3), 1);
    }

当我从uv2调用compareTo时,这是null,我有NullReferenceException所以......我怎么能满足给定的限制?

1 个答案:

答案 0 :(得分:0)

如果您想比较 arbitraty 实例(包括null两种情况),您必须实现静态方法,因为

  this == null

是任何成员函数中的不可能条件。因此异常的直接原因是在null实例上调用成员函数:

UserView uv2 = null;
// Since uv2 is null, Null Exception will be thrown
uv2.CompareTo(uv3);

一种出路是static方法:

public int CompareTo(UserView other) 
{
    return UserView.Compare(this, other);   
}

// please, note "static" 
public static int Compare(UserView left, UserView right)
{
    if (left == null)
      if (right == null) 
        return 0;
      else 
        return -1;
    else if (right == null) 
      return 1; 
    else // Providing that Id can't be null (e.g. it's int)
      return left.Id.CompareTo(right.Id); 
}

....

UserView uv2 = null;
UserView uv3 = null;

// uv2.CompareTo(uv3) will throw Null Exception and
// ... static UserView.Compare will do
Assert.AreEqual(UserView.Compare(uv2, uv3), -1);