2015-04-29 101 views
0

不同对象的名单我有一个基类如下初始化继承

protected BaseClasse() 
    { 
     this.myDic= new Dictionary<string, List<somethingThatWillChange>>(); 
    } 

    protected Dictionary<string, List<somethingThatWillChange>> myDic{ get; set; } 

然而,这个类将有两班,将继承它。其中一个遗传类需要new Dictionary<string, List<Type1>>(),另一个需要new Dictionary<string, List<Type2>>()。 Type1和Type2是类,Type1有7个字段(名称,年龄,时间,工作,汽车,薪水,标题),Type2有3个字段(名称,年龄,时间)。

因此在基类中,我要初始化或声明我的词典为new Dictionary<string, List<somethingGeneric>>()

,然后在这两个继承类,我要初始化或转换为适当的List<type1>List<type2>

  • 我不想声明多个字典。
  • 我不想做我的Type1和Type2类

继承是有办法做到这一点?

回答

6

使用generics

public BaseClass<T> 
{ 
    protected BaseClasse() 
    { 
     this.myDic= new Dictionary<string, List<T>>(); 
    } 

    protected Dictionary<string, List<T>> myDic{ get; set; } 
} 
3

这应该工作:

public BaseClass<T> { 
    protected BaseClass() 
    { 
     this.myDic = new Dictionary<string, List<T>>(); 
    } 

    protected Dictionary<string, List<T>> myDic { get; set; } 
} 

public Type1Class : BaseClass<Type1> { 
} 

public Type2Class : BaseClass<Type2> { 
}