繁体   English   中英

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

[英]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; }
}

看起来你想要做的是确保这个类的属性是一个 ICollection,但在这种情况下你不需要指定。

如果你想确保你的属性是一个通用的可枚举类型,你可以通过指定它是一个双精度的 IEnumerable 来实现。 或者,如果您想确保它是一种 ICollection,那么您也可以将您的财产声明为 -

public ICollection<double> ListOfDoubles {get;set}

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

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

然后将此集合用于您的应用程序。 以下代码显示了如何执行此操作,您可以添加所需的任何方法

 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; }
}

你可以看到这个页面

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM