我想为通用数组编写一个 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 编译的)。谁能帮我 ?