Express C#泛型类型参数更简洁?

时间:2012-03-11 20:36:55

标签: c# generics generic-type-argument

受启发

Comparing two collections for equality irrespective of the order of items in them

我创建了一个扩展方法来测试两个集合是否相同。要使用扩展方法,我必须指定两个类型参数,如下所示:

IsEquivalentToTestHelper<ObservableCollection<string>, string>(first, second, true);

有没有办法实现扩展方法,只需要指定一个通用约束(例如ObservableCollection<string>)?

更新:根据答案additional response将修改后的代码发布到启发此问题的问题上。

这是我的原始代码:

static public class EnumerableExtensions 
{
    static public bool IsEquivalentTo<E,T>(this E first, E second) where E : IEnumerable<T>
    {
        if ((first == null) != (second == null))
            return false;

        if (!object.ReferenceEquals(first, second) && (first != null))
        {
            if (first.Count() != second.Count())
                return false;

            if ((first.Count() != 0) && HaveMismatchedElement<E,T>(first, second))
                return false;
        }

        return true;
    }

    private static bool HaveMismatchedElement<E,T>(E first, E second) where E : IEnumerable<T>
    {
        int firstCount;
        int secondCount;

        var firstElementCounts = GetElementCounts<E,T>(first, out firstCount);
        var secondElementCounts = GetElementCounts<E,T>(second, out secondCount);

        if (firstCount != secondCount)
            return true;

        foreach (var kvp in firstElementCounts)
        {
            firstCount = kvp.Value;
            secondElementCounts.TryGetValue(kvp.Key, out secondCount);

            if (firstCount != secondCount)
                return true;
        }

        return false;
    }

    private static Dictionary<T, int> GetElementCounts<E,T>(E enumerable, out int nullCount) where E : IEnumerable<T>
    {
        var dictionary = new Dictionary<T, int>();
        nullCount = 0;

        foreach (T element in enumerable)
        {
            if (element == null)
            {
                nullCount++;
            }
            else
            {
                int num;
                dictionary.TryGetValue(element, out num);
                num++;
                dictionary[element] = num;
            }
        }

        return dictionary;
    }

    static private int GetHashCode<E,T>(IEnumerable<T> enumerable) where E : IEnumerable<T>
    {
        int hash = 17;

        foreach (T val in enumerable.OrderBy(x => x))
            hash = hash * 23 + val.GetHashCode();

        return hash;
    }
}

3 个答案:

答案 0 :(得分:4)

static public bool IsEquivalentTo<T>(this IEnumerable<T> first, IEnumerable<T> second) 

答案 1 :(得分:2)

您可以删除第一个并保留第二个:

static public bool IsEquivalentTo<T>(this IEnumerable<T> first, IEnumerable<T> second)

答案 2 :(得分:1)

您只需将每个E替换为IEnumerable<T>,然后删除where语句

例如:

static public bool IsEquivalentTo<T>(this IEnumerable<T> first, IEnumerable<T> second)

var firstElementCounts = GetElementCounts<IEnumerable<T>,T>(first, out firstCount);

static private int GetHashCode<T>(IEnumerable<T> enumerable)