C#force继承了循环遍历列表的类

时间:2012-11-21 22:24:48

标签: c#

例如,我有两个类:

Class A
{
  string property1;
  string property2;
}

Class B : A
{
  string property3;
  string property4;
  ....
} 

所以B继承了A类的属性。他们坐在列表中,就是坐在字典里

Dictionary <string, List<A>> myDictionary = new Dictionary<string, List<A>>();

List<A> myList = new List<A>();

有一个包含许多List的词典,它们都包含A类和A类的混合。 B对象。 循环时,我试图从类B对象访问一些属性,我有一个if语句来找到它们但程序仍然认为它们是类A类,并在我尝试使用property3或property4时抛出错误。例如:

string key = string key in dictionary;
string index = object position in list;

myDictionary[key][index].property3.someMethod();

有没有办法告诉程序这是一个B类对象并允许属性3&amp; 4要用吗?

1 个答案:

答案 0 :(得分:5)

将对象安全地转换为B类型对象,然后检查null

var obj = myDictionary[key][index];

var bObj = obj as B;
if (bObj != null)
{
     bObj.someMethod();
}

虽然,我也可能会说你的设计看起来很糟糕。通常,我不会指望这样的事情。通常,如果您正在使用继承,那么您需要一种允许它们互换使用的设计。例如,您可以将A上的行为实现为无操作,但在B上覆盖它以实际执行某些操作。这将使得消费类无需关心“A”事物是否真的是A或B实例。