需要使用大于或小于比较两个通用对象

时间:2012-07-23 15:54:32

标签: c# comparison

概要:我需要使用两个通用C#对象,如果它们是数字对象,则使用小于或大于比较的方式对它们进行比较。

问题:我无法弄清楚如何让我的类实现IComparable,如本文所述:Having to implement a generic less than and greater than operation。如果这还不是正确的道路,那么我也需要知道。

背景:我已在A more complex custom validator处实现了RequiredIf ValidationAttribute但需要>和<除了等于比较之外的选项。

代码(取自A more complex custom validator,页面下方三分之一):

private bool IsRequired(object actualPropertyValue)
{
  switch (Comparison)
  {
    case Comparison.IsLessThan:
    case Comparison.IsLessThanOrEqualTo:
    case Comparison.IsGreaterThan:
    case Comparison.IsGreaterThanOrEqualTo:
      if (!Value.IsNumber())
      {
        throw new Exception("The selected comparison option is only applicable to numeric values");
      }
      break;
  }

  switch (Comparison)
  {
    case Comparison.IsNotEqualTo:
      return actualPropertyValue == null || !actualPropertyValue.Equals(Value);
    case Comparison.IsEqualTo:
      return actualPropertyValue != null && actualPropertyValue.Equals(Value);
    case Comparison.IsGreaterThan:
      // THIS LINE FAILS BECAUSE actualPropertyValue DOESN'T IMPLEMENT IComparable 
      return actualPropertyValue != null && (actualPropertyValue.CompareTo(Value) > 0); 
    // The rest of the comparison cases go here...
    default:
      throw new Exception("Comparison value is not defined");
  }
}

静态助手扩展程序:

public static bool IsNumber(this object value)
{
  if (value is sbyte) return true;
  if (value is byte) return true;
  if (value is short) return true;
  if (value is ushort) return true;
  if (value is int) return true;
  if (value is uint) return true;
  if (value is long) return true;
  if (value is ulong) return true;
  if (value is float) return true;
  if (value is double) return true;
  if (value is decimal) return true;
  return false;
}

2 个答案:

答案 0 :(得分:13)

听起来你应该能够将actualPropertyValue投射到IComparable

IComparable comparable = (IComparable) actualPropertyValue;
return comparable != null && comparable.CompareTo(Value) > 0;

请注意,您对“通用”一词的使用很奇怪。如果实际使其成为通用的,您可以写:

private bool IsRequired<T>(T actualPropertyValue) where T : IComparable

然后你不需要演员。

答案 1 :(得分:3)

int MyCompare (object a, object b)
{
   var ac = a as IComparable;
   var bc = b as IComparable;

    if (ac == null || bc == null)
       throw new NotSupportedException();

    return ac.CompareTo(bc);
 }