2012-09-21 47 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