通用 class 并为集合字段选择基础集合

Generic class and choosing an underlying collection for the collection fields

我想做这样的事情:

public class SomeClass<T> where T: ICollection
{
    public T<double> ListOfDoubles { get; set; }
    public T<int> ListOfIntegers { get; set; }
}

但是,我遇到的问题是 ICollection 需要一个类型参数 我该如何解决这个问题? 我找不到确切的答案,可能是我没有很好地制定我的搜索。

你可以这样做 -

public class MyClass
{
  public ICollection<double> ListOfDoubles { get; set; }
}

您似乎想做的是确保此 class 的属性是一个 ICollection,但在这种情况下您不需要指定它。

如果您想确保您的 属性 是一个通用的可枚举类型,您只需指定它是一个 IEnumerable of double 即可。或者如果你想确保它是一种 ICollection 那么你也可以将你的 属性 声明为 -

public ICollection<double> ListOfDoubles {get;set}

即使编译器允许你做你正在做的事情,你也不会得到任何东西,因为你可以自己将 属性 声明为 ICollection,它已经是泛型类型了。

最好创建自己的 collection 并根据您的个人品味进行定制。

然后将此 Collection 用于您的应用程序。下面的代码展示了如何做到这一点,你可以添加任何你想要的方法

 public class SimpleCollection<T> : ICollection<T>
{

   ICollection<T> _items;


   public SimpleCollection()
   {
       // Default to using a List<T>.
        _items = new List<T>();
   }

   protected SimpleCollection(ICollection<T> collection)
   {
      // Let derived classes specify the exact type of ICollection<T> to wrap.
      _items = collection;
   }

   public void Add(T item)
   {
       _items.Add(item);
   }

   public void Clear()
   {
       _items.Clear();
   }

   public bool Contains(T item)
   {
       return _items.Contains(item);
   }

   public void CopyTo(T[] array, int arrayIndex)
   {
       _items.CopyTo(array, arrayIndex);
   }

   public int Count
   {
       get { return _items.Count; }
   }

   public bool IsReadOnly
   {
       get { return false; }
   }

   public bool Remove(T item)
   {
       return _items.Remove(item);
   }

   public IEnumerator<T> GetEnumerator()
   {
       return _items.GetEnumerator();
   }

   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
   {
       return _items.GetEnumerator();
   }
}

现在使用

public class SomeClass
{
   public SimpleCollection<double> ListOfDoubles { get; set; };
   public SimpleCollection<int> ListOfIntegers { get; set; }
}

你可以看到这个page