0

我有一个代码可以很好地比较字符串列表,如下所示。现在我想将其转换为泛型,我尝试将相同的代码转换为泛型,但尽管进行了多次纠正,但仍然出现错误。由于我是仿制药新手,因此我需要专家来指导我做错了什么。

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 上使用字符串函数。

4

1 回答 1

1

Regex.Split()返回 a string[],但您已将strFirst和定义strSecond为泛型参数类型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);
}
于 2013-07-16T12:40:02.760 回答