我有一堆实现IComparable<T>
. 因为这些类型实现了该接口,所以提供以下重载是有意义的:
/// <summary>Equality comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is equal to <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator==(T lhs, T rhs)
{
if (object.ReferenceEquals(lhs, null))
{
return object.ReferenceEquals(rhs, null);
}
return lhs.CompareTo(rhs) == 0;
}
/// <summary>Inequality comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is not equal to <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator !=(T lhs, T rhs)
{
return !(lhs == rhs);
}
/// <summary>Less than comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is less than <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator <(T lhs, T rhs)
{
if (lhs == null)
{
if (rhs == null)
{
return false;
}
else
{
return true;
}
}
else
{
return lhs.CompareTo(rhs) < 0;
}
}
/// <summary>Greater than comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is greater than <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator >(T lhs, T rhs)
{
return rhs < lhs;
}
/// <summary>Less than or equal comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is less` than or equal to <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator <=(T lhs, T rhs)
{
return !(rhs < lhs);
}
/// <summary>Greater than or equal comparison operator.</summary>
/// <param name="lhs">The left hand side.</param>
/// <param name="rhs">The right hand side.</param>
/// <returns>True if <paramref name="lhs"/> is greater than or equal to <paramref name="rhs"/>; otherwise, false.</returns>
public static bool operator >=(T lhs, T rhs)
{
return !(lhs < rhs);
}
这是大量重复的代码。是否有一些方法可以创建一个抽象类或其他东西(例如 C++'s std::rel_ops
),这样可以更容易地实现这些?