我想做这样的事情:
public class SomeClass<T> where T: ICollection
{
public T<double> ListOfDoubles { get; set; }
public T<int> ListOfIntegers { get; set; }
}但是,我遇到的问题是,ICollection需要一个类型论证,如何绕过这个问题?我找不到确切的答案,可能我的搜索不够好。
发布于 2021-07-22 10:33:25
你可以这么做-
public class MyClass
{
public ICollection<double> ListOfDoubles { get; set; }
}似乎您要做的是确保这个类的属性是一个ICollection,但是在这种情况下您不需要指定它。
如果要确保您的属性是泛型可枚举类型,只需指定它是一个IEnumerable,就可以做到这一点。或者,如果您想确保它是一种ICollection类型,那么您也可以将您的属性声明为-
public ICollection<double> ListOfDoubles {get;set}即使编译器允许您做您正在做的事情,您也不会获得任何结果,因为您可以自己声明属性为ICollection,它已经是泛型类型。
发布于 2021-07-22 10:50:04
最好是创建你自己的收藏,并根据你的个人品味定制它。
然后将此集合用于您的应用程序。下面的代码演示了如何做到这一点,您可以添加任何您想要的方法
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; }
}你可以看到这个
https://stackoverflow.com/questions/68482479
复制相似问题