[英]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.