尝试将字符串比较转换为Generic

时间:2013-07-16 12:35:47

标签: c# generics compareto

我有一个代码可以很好地比较字符串列表,如下所示。现在我想将其转换为泛型,我已经尝试将相同的代码转换为泛型,但我遇到了错误,尽管有许多尝试纠正它。由于我是仿制药的新手,我需要专家的手来指导我做错的事。

public class BaseComparer<T> : IComparer<T>, IDisposable where T : IBaseComparer<T>
{
    private Dictionary<T, T[]> Value;

    public BaseComparer()
    {
        Value = new Dictionary<T, T[]>();
    }

        public int Compare(T lhs, T rhs)
        {
            if (lhs.Equals(rhs))
                return 0;

            T[] strFirst, strSecond;

            if (!Value.TryGetValue(lhs, out strFirst))
            {                
                strFirst = Regex.Split(lhs.ToString().Replace(" ", ""), "([0-9]+)");
                strFirst = Regex.Split(lhs.ToString().Replace("|", ">>"), "([0-9]+)");
                Value.Add(lhs, strFirst);
            }

            if (!Value.TryGetValue(rhs, out strSecond))
            {
                strSecond = Regex.Split(rhs.ToString().Replace(" ", ""), "([0-9]+)");
                strSecond = Regex.Split(rhs.ToString().Replace("|", ">>"), "([0-9]+)");

                Value.Add(rhs, strSecond);
            }

            for (int i = 0; i < strFirst.Length && i < strSecond.Length; i++)
            {
                if (!strFirst[i].Equals(strSecond[i]))
                {
                    return Splitcompare(strFirst[i], strSecond[i]);
                }
            }
            if (strSecond.Length > strFirst.Length)
            {
                return 1;
            }
            else if (strFirst.Length > strSecond.Length)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }

        private static int Splitcompare(string left, string right)
        {
            int x, y;
            if (!int.TryParse(left.ToString(), out x))
            {
                return left.CompareTo(right);
            }

            if (!int.TryParse(right.ToString(), out y))
            {
                return left.CompareTo(right);
            }

            return x.CompareTo(y);
        }
   }

当我尝试在Regex线上使用Replace时,上面的代码给出了错误。原因是,我不能在T上使用字符串函数。

1 个答案:

答案 0 :(得分:1)

Regex.Split()会返回string[],但您已将strFirststrSecond定义为通用参数类型T。试试这个:

private Dictionary<T, string[]> Value;

public BaseComparer()
{
    Value = new Dictionary<T, string[]>();
}

string[] strFirst, strSecond;

if (! Value.TryGetValue(lhs, out strFirst))
{                
    strFirst = Regex.Split(lhs.ToString().Replace(" ", ""), "([0-9]+)");
    strFirst = Regex.Split(lhs.ToString().Replace("|", ">>"), "([0-9]+)");
    Value.Add(lhs, strFirst);
}

if (! Value.TryGetValue(rhs, out strSecond))
{
    strSecond = Regex.Split(rhs.ToString().Replace(" ", ""), "([0-9]+)");
    strSecond = Regex.Split(rhs.ToString().Replace("|", ">>"), "([0-9]+)");
    Value.Add(rhs, strSecond);
}