【问题标题】:C# ICollection extensionC# ICollection 扩展
【发布时间】:2012-09-21 05:00:14
【问题描述】:

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

【问题讨论】:

  • 您的方法未设置为使用泛型类型...public static T[] Add&lt;T&gt;(...) { } 是正确的格式。

标签: c# arrays generics unity3d


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以只使用 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();
        }
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

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

        List<string> arr = new List<string>();
        arr.AddIfNotExists("a");
        

        【讨论】:

          猜你喜欢
          • 2013-09-08
          • 2017-03-12
          • 2014-02-19
          • 2019-01-19
          • 2013-06-24
          • 1970-01-01
          • 2019-04-23
          • 1970-01-01
          • 2018-03-06
          相关资源
          最近更新 更多