如何在C#中创建一个通用方法,它适用于许多类型 - 整数,字符串,双精度等

sat*_*jit 2 c# generics

让我有一个方法来删除整数数组中的重复项

 public int[] RemoveDuplicates(int[] elems)
    {
        HashSet<int> uniques = new HashSet<int>();
        foreach (int item in elems)
            uniques.Add(item);
        elems = new int[uniques.Count];
        int cnt = 0;
        foreach (var item in uniques)
            elems[cnt++] = item;
        return elems;
    }
Run Code Online (Sandbox Code Playgroud)

我如何使这个泛型,现在它接受一个字符串数组并删除它中的重复项?双阵列怎么样?我知道我可能在原始和价值类型之间混合了一些东西.供您参考,以下代码将无法编译

 public List<T> RemoveDuplicates(List<T> elems)
        {
            HashSet<T> uniques = new HashSet<T>();
            foreach (var item in elems)
                uniques.Add(item);
            elems = new List<T>();
            int cnt = 0;
            foreach (var item in uniques)
                elems[cnt++] = item;
            return elems;
        }
Run Code Online (Sandbox Code Playgroud)

原因是所有泛型类型都应在运行时关闭.谢谢你的评论

Are*_*ren 6

    public List<T> RemoveDuplicates<T>(List<T> elems)
    {                           //  ^
        HashSet<T> uniques = new HashSet<T>();
        foreach (var item in elems)
            uniques.Add(item);
        elems = new List<T>();
        int cnt = 0;
        foreach (var item in uniques)
            elems[cnt++] = item;
        return elems;
    }
Run Code Online (Sandbox Code Playgroud)

然后你称之为:

.RemoveDuplicates<string>(new List<string>{ "hello", "hello", "world" });
Run Code Online (Sandbox Code Playgroud)

但是,我建议你使用这段代码:

public IList<T> RemoveDuplicates<T>(IEnumerable<T> elems)
{                            //  ^
    IList<T> uniques = new List<T>();
    foreach(T item in elems)
       if(!uniques.Contains(item))
          uniques.Add(item);

    return uniques;
}
Run Code Online (Sandbox Code Playgroud)

这条路

  1. 你的函数可以使用任何IEnumerable(这包括IList,或者我们可以枚举的任何东西)
  2. 您的功能更简单,但对于大型数据集可能效率不高,但这取决于您的平均数据大小.如果您希望提高效率而不是大型数据集,您可以简单地使用IEnumerable <>组件并从那里开始.
  3. 它返回一个IList <>,它更通用.

或者,如果您可以访问.NET 3.0/3.5/4.0,请像建议的其他答案一样使用linq.希望这有助于说明通用方法.