2012-09-21 46 views
1

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

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编译的)。谁能帮我 ?

+1

你的方法是不设置为使用通用类型...'public static T [] Add (...){}'是正确的格式。 –

回答

2

由于缺少对System.Collections.Generic命名空间的引用,所以上次的方法不能编译。您似乎只包含对System.Collections的引用。

+0

这正是问题所在,谢谢。它正在工作! – thienhaflash

+2

那么,你必须接受他的回答! –

+0

谢谢你,我对stackoverflow系统有点新鲜。 – thienhaflash

0

您可以将方法签名改成这样:

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

然而,也有T []所以list.IndexOf(item)不会编译没有通用的方法。

0

你最后的代码应该工作IF称其为字符串数组,为数组有固定的尺寸!

以下为例对我的作品与使用您的扩展方法ICollection

List<string> arr = new List<string>(); 
arr.AddIfNotExists("a"); 
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(); 
    } 
+0

感谢的人,这是工作,非常紧凑! – thienhaflash