这是一个常见问题的简单示例:
有一个常见的问题,可以用一个简单的例子来说明:
ICollection<int> myIntegers = ....
ICollection<string> myStrings = ....
在某些时候,我需要将这些实例以及其他类型传递给那些被声明为IEnumerable(非泛型形式)的方法。
如果不通过反射来进行后门操作,那么这段代码就无法确定:
1. That the instance is a constructed type of ICollection<T>
2. The number of elements in the ICollection<T>-based type.
不知道泛型参数是什么。
当我定义一个泛型类型,提供的操作不依赖于泛型参数类型 (例如 ICollection 的 Count 属性),我一般会定义一个非泛型的基础类型,并将不依赖于类型的操作放在那里,像这样:
public abstract class FrugalList
{
public abstract int Count {get;}
}
public class FrugalList<T> : FrugalList
{
public override int Count {get{...}}
void Add(T item) {...}
}
鉴于此,我可以使用抽象基类型轻松获取任何构建在通用类型定义上的实例的计数。
那么,问题非常简单,您认为提供此功能(也可以通过接口完成)是否重要?