简体   繁体   English

C#/通过foreach访问时访问列表中子类的方法

[英]C# / accessing methods of sub-classes in a list when accessing through foreach

Trying to understand how to access the methods of a sub-class when the list is typed as the superclass. 试图了解如何在将列表键入为超类时访问子类的方法。 This should be basic polymorphism, but I'm getting confused. 这应该是基本的多态性,但是我感到困惑。

public class super
{ 
  public Boolean isSuper()
  {
    return true;
  }
}

public class sub : super
{ 
  public Boolean isSuper()
  {
    return false;
  }
}

Now I make a list of these objects 现在,我列出这些对象

List <super> myList = new List<super>();
myList.Add(new super());
myList.Add(new sub());

Now I try to get each object in the list to query itself to see if it is a super-class or a sub-class 现在,我尝试获取列表中的每个对象以查询自身,以查看它是超类还是子类

foreach(super objInList in myList)
{
  if(objInList.isSuper())
    Debug.Print("Super");
  else
    Debug.Print("Sub");
}

So what happens is that since each object is cast as a super-class, it uses the super-class method of isSuper() and it always responds as a super-class. 因此发生的事情是,由于每个对象都被强制转换为超类,因此它使用isSuper()的超类方法,并且始终将其作为超类进行响应。

I want to access the sub-classes' isSuper() without having to use an instanceof in every single iteration of the loop. 我想访问子类的isSuper(),而不必在循环的每次迭代中都使用instanceof Obviously if you can query the object to see if it is a super or a sub, then something in the O/S knows the type of object. 显然,如果您可以查询对象以查看它是父对象还是子对象,则操作系统中的某些对象便知道对象的类型。 Why go through a guessing game of checking each possibility? 为什么要进行检查每种可能性的猜谜游戏? Why not ask it to drill down to the appropriate sub-class and execute the appropriate method? 为什么不要求它深入到适当的子类并执行适当的方法? Is there a way to achieve this goal? 有没有办法实现这个目标?

You have to override super class property in your sub class to get required behaviuor. 您必须在sub类中重写 super类属性才能获得所需的行为。

Change your class definitions accordingly: 相应地更改您的类定义:

public class super
{ 
  public virtual Boolean isSuper()
  {
    return true;
  }
}

public class sub : super
{ 
  public override Boolean isSuper()
  {
    return false;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM