1

我想为通用数组编写一个 C# 扩展,但它总是抛出一个错误。这是我用来为 string[] 创建扩展的代码,效果很好:

public static string[] Add(this string[] list, string s, bool checkUnique = false, bool checkNull = true){
    if (checkNull && string.IsNullOrEmpty(s)) return list;
    if (checkUnique && list.IndexOf(s) != -1) return list;

    ArrayList arr = new ArrayList();
    arr.AddRange(list);
    arr.Add(s);

    return (string[])arr.ToArray(typeof(string));
}

我真正想要的是让它更通用,因此它不仅适用于字符串,也适用于其他类型(所以我试图用泛型 T 替换所有字符串细节):

public static T[] Add(this T[] list, T item, bool checkUnique = false){
    if (checkUnique && list.IndexOf(item) != -1) return list;

    ArrayList arr = new ArrayList();
    arr.AddRange(list);
    arr.Add(item);

    return (T[])arr.ToArray(typeof(T));
}

但代码不会编译。它正在投射错误“错误 CS0246:找不到类型或命名空间名称‘T’。您是否缺少 using 指令或程序集引用?”

我已经尝试了另一种解决方案:

public static void AddIfNotExists<T>(this ICollection<T> coll, T item) {
     if (!coll.Contains(item))
         coll.Add(item);
 }

但它正在投射另一个错误“错误 CS0308:非泛型类型 `System.Collections.ICollection' 不能与类型参数一起使用”

作为旁注,我使用的是 Unity C#(我认为它是针对 3.5 编译的)。谁能帮我 ?

4

4 回答 4

2

由于缺少对 System.Collections.Generic 命名空间的引用,您的最后一个方法无法编译。您似乎只包含了对 System.Collections 的引用。

于 2012-09-21T05:19:48.750 回答
1

您可以只使用 LINQ 并使您的方法更简单一些:

    public static T[] Add<T>(this T[] list, T item, bool checkUnique = false)
    {
        var tail = new [] { item, };
        var result = checkUnique ? list.Union(tail) : list.Concat(tail);
        return result.ToArray();
    }
于 2012-09-21T05:43:37.737 回答
0

您可以将方法签名更改为:

public static T[] Add<T>(this T[] list, T item, bool checkUnique = false)
{}

但是,T[] 没有通用方法,因此list.IndexOf(item)无法编译。

于 2012-09-21T05:15:42.623 回答
0

如果为字符串数组调用它,您的最后一个代码应该可以工作,因为数组具有固定的大小!

以下示例适用于您使用的扩展方法ICollection

List<string> arr = new List<string>();
arr.AddIfNotExists("a");
于 2012-09-21T05:29:49.070 回答