【发布时间】:2015-11-18 17:19:39
【问题描述】:
我有一个包含许多不同类型的通用集合的类。
public class InMemoryDatabase
{
public HashSet<Car> Cars { get; set; }
public HashSet<Truck> Trucks { get; set; }
public HashSet<Bike> Bikes { get; set; }
}
如何根据泛型类型检索集合?
例如
public HashSet<TEntity> GetCollection<TEntity>()
{
//how to retrieve collection from InMemoryDatabase class?
}
可以这样调用:
HashSet<Bike> = GetCollection<Bike>();
更新
请注意,GetCollection 方法的实现不应该事先知道 InMemoryDatabase 类中的集合类型,因为它是从基类调用的。解决方案应该是通用的。我想使用反射可能是一种可能的方法?
【问题讨论】:
-
你能解释一下你为什么需要这个吗?可能有更好的方法。
-
HashSet<Bike> = instanceOfInMemoryDatabase.Bike? -
我同意伊恩的观点,如果你已经知道你想要的类型,那么为什么不直接访问你想要的属性呢?除非您有共同的祖先或接口,否则返回特定的哈希集类型没有多大意义
-
var trucks = yourCollection.OfType
()
标签: c# generics collections