如何在 C# 中使用 compareTo 对空对象进行排序
How to order null objects with compareTo in C#
我有一个名为 UserView 的 class,我实现了他的 compareTo() 方法。
我有那个限制:"If a UserView is compared with a null UserView, the null go before the other"
我有 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 时,它是空的,我有 NullReferenceException 所以...我怎样才能满足给定的限制?
如果你想比较 arbitraty 实例(包括两个 null
案例)你必须实现一个 static 方法,因为
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);
我有一个名为 UserView 的 class,我实现了他的 compareTo() 方法。
我有那个限制:"If a UserView is compared with a null UserView, the null go before the other"
我有 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 时,它是空的,我有 NullReferenceException 所以...我怎样才能满足给定的限制?
如果你想比较 arbitraty 实例(包括两个 null
案例)你必须实现一个 static 方法,因为
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);