在foreach循环中调用派生类的方法 [英] Calling derived class methods in a foreach loop

查看:164
本文介绍了在foreach循环中调用派生类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



I'm having trouble with this piece of code:

List<Person> persons;    

foreach(var p in persons)
    p.Save();

Person 其中有自己的新的Save()方法。不幸的是,上面的代码只调用了基类的save方法,尽管这个列表包含了不同类型(基类和派生类)的实例。

There are several classes derived from Person all of which have their own new Save() method. Unfortunately, the above code only calls the base class' save method, despite the fact that the list contains instances of different types (base class and derived ones).

类包含所有基类的字段,只有 Save 方法是不同的,所以它也保存了派生类的字段。

All derived classes contain all of the base class' fields, only the Save method is different so it also saves the derived class' fields.

如何根据当前正在迭代的变量类型调用相应的 Save 方法?

How do I make that loop call the appropriate Save method based on the variable type it's currently iterating through?

推荐答案

方法隐藏通常是灾难的秘诀。这个场景的一个正确的实现是在 Person 中声明 Save() virtual code> class和 override 在派生类中。

Method hiding is generally a recipe for disaster. A correct implementation of this scenario would declare Save() as virtual in the Person class and override it in derived classes.

你需要将 p 转换为适当的派生类,然后调用 Save()。根据你对对象所做的或不知道的事情,你可能需要动态地确定派生类型,并使用反射来调用它的 Save()方法。

For it to work in your case as described above you would need to cast p to the appropriate derived class and call Save() on it. Depending on what you do or don't know about the object, you may need to dynamically determine the derived type and invoke its Save() method using reflection.

这篇关于在foreach循环中调用派生类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆