通用对象列表

时间:2014-01-23 12:43:36

标签: c# .net list generics

我有一个像这样的ContextBase类:

public class ContextBase<T, TK> where T : IIdAble<TK>, new()
{

}

包含一些ContextBases的类:

public static class Context
{
    private static ContextBase<Action, int> _actionContext;
    private static ContextBase<Customer, long> _customerContext;
}

现在,我可以将这两个ContextBase放在一个List中吗?我在Context中需要这样的东西:

private static List<ContextBase<T,K>> _contexts;

我可以使用ArrayList但是可以使用泛型吗?

3 个答案:

答案 0 :(得分:1)

不,这是不可能的。这就像询问是否可以将字符串和整数存储在比List<object>更具体的内容中。

由于objectContextBase<Action, int>ContextBase<Customer, long>的唯一公共基类,因此您只能使用List<object>将两者存储在同一列表中。

但是,您可以使它们实现一个公共(非泛型)接口IContextBase,其中包含您需要对这些列表项执行的所有功能,并ContextBase<T, TK>实现IContextBase }。然后,您可以使用List<IContextBase>

答案 1 :(得分:1)

您将无法安全地执行此类型。但是,你不需要像ArrayList那样不安全。

public class ContextBase<T, TK> : IContextBase where T : IIdAble<TK>, new()
                                  ^          ^

制作ContextBase实施的非通用界面,然后使用List<IContextBase>

不幸的是,您仍然无法使用ContextBase的通用成员,但这是您必须支付的最低价格。

答案 2 :(得分:1)

因为ContextBase被定义为ContextBase<T, TK> where T : IIdAble<TK>,这意味着编译器会看到ContextBase<Action, int>ContextBase<Customer, long>作为要求List<ContextBase<T,K>>的单独类几乎相同要求列表的int,长期它违反了通用列表的意图。你可以做的是拥有一个ContextBase<Action, int>ContextBase<Customer, long>共同的类列表。

public class ContextBase<T, TK> : CommonClass where T : IIdAble<TK>, new(){...}

然后

private static List<CommonClass> _contexts = new List<CommonClass>{
  new ContextBase<Action, int>(), 
  new ContextBase<Customer, long>()
};
相关问题