泛型可以用来组合这些方法吗?

时间:2011-01-26 16:56:48

标签: c# generics

我正在尝试根据文件的输入设置比较(即两个值在XML选项文件中并读入,我想比较它们。)

我能做到这一点,但看起来有点冗长。我想我会在这里发布,看看是否有办法通过Generics完成我的比较。

以下是我的方法:

// Only equal is supported for strings.
public static bool CompareString(this ComparisionOperator oper, string leftSide, string rightSide)
{
    return leftSide == rightSide;
}


public static bool CompareDouble(this ComparisionOperator oper, double leftSide, double rightSide)
{
    switch (oper)
    {
        case ComparisionOperator.LessThan:
            return leftSide < rightSide;
        case ComparisionOperator.GreaterThan:
            return leftSide > rightSide;
        case ComparisionOperator.LessThanOrEqualTo:
            return leftSide <= rightSide;
        case ComparisionOperator.GreaterThanOrEqualTo:
            return leftSide >= rightSide;
        case ComparisionOperator.EqualTo:
            return leftSide == rightSide;
        default:
            throw new ArgumentOutOfRangeException("oper");
    }
}


public static bool CompareDateTime(this ComparisionOperator oper, DateTime leftSide, DateTime rightSide)
{
    switch (oper)
    {
        case ComparisionOperator.LessThan:
            return leftSide < rightSide;
        case ComparisionOperator.GreaterThan:
            return leftSide > rightSide;
        case ComparisionOperator.LessThanOrEqualTo:
            return leftSide <= rightSide;
        case ComparisionOperator.GreaterThanOrEqualTo:
            return leftSide >= rightSide;
        case ComparisionOperator.EqualTo:
            return leftSide == rightSide;
        default:
            throw new ArgumentOutOfRangeException("oper");
    }
}

//  Repeated for Int (and maybe GUID)

我最好重复这些吗?

我遇到的问题是比较字符串与比较数字或日期时间不同。如果我只是创建一个泛型方法并传入一个字符串,如果它尝试少于一个字符串,它是否会感到困惑?

2 个答案:

答案 0 :(得分:3)

您可以通过限制实现IComparable<T>的类型,使用某些类型的泛型来重构此内容。

public static bool Compare<T>(this ComparisionOperator oper, T leftSide, T rightSide)
    where T : IComparable<T>
{
    switch (oper)
    {
        case ComparisionOperator.LessThan:
            return leftSide.CompareTo(rightSide) < 0;
        case ComparisionOperator.GreaterThan:
            return leftSide.CompareTo(rightSide) > 0;
        case ComparisionOperator.LessThanOrEqualTo:
            return leftSide.CompareTo(rightSide) <= 0;
        case ComparisionOperator.GreaterThanOrEqualTo:
            return leftSide.CompareTo(rightSide) >= 0;
        case ComparisionOperator.EqualTo:
            return leftSide.CompareTo(rightSide) == 0;
        default:
            throw new ArgumentOutOfRangeException("oper");
    }
}

这适用于多种类型,因为Int32DoubleSingle等都会实施IComparable<T>

答案 1 :(得分:0)

  如果它试图做一个小于字符串的话,会不会感到困惑?

您的程序将崩溃,因为没有为String类定义那些运算符。您可以接受将为您进行比较的IComparer,并且该比较器可以定义一个字符串对于“小于”“大于”另一个字符串的含义。