Pergunta

I have a base class called Graphic_obj.

And i have many derived classes, for example: Graphic_obj_text, Graphic_obj_img, ...

Now i want to have a list with all of my created derived objects..

List<Graphic_obj> obj_list=new List<Graphic_obj>();

now my problem comes up..

i want to go thru my objects and call an "export" function for each, but from the derived class itself!

i don't want to if/else or switch all the type's of derived classes and cast them..

i would imagine something like this:

foreach (Graphic_obj obj in obj_list)
{
    (obj as obj.GetType()).export_to_csv();
}

but this will not compile..

i can do it like this way:

obj.GetType().GetMethod("export_to_csv").Invoke(obj, null);

but i think there is a pretty better and easier way ?!

thank you!

Foi útil?

Solução

Just make export_to_csv virtual and override it in the derived classes. You can implement common functionality in the base export_to_csv, and the derived classes can call it.

class Graphic_obj {
    virtual void export_to_csv(){
        // Do stuff that's common across all classes
    }
}

class Graphic_obj_text : Graphic_obj {
    override void export_to_csv(){
        base.export_to_csv():
        // Do stuff specific to Graphic_obj_text
    }
}

Outras dicas

The technique you actually need is called Polymorphism. You may define a function in your parent, and provide implementation in respective children, accordingly. HERE is a simple example from MSDN.

To my understanding you are asking for virtual methods, which are described here; they are there for exactly the purpose you are describing.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top