lundi 11 juin 2018

Control structure scope and casting interface to concrete object

I was trying to write this code a bit more proper by reducing repeated code.

private void makeNewItem(IMovingObject item)
{
    if (item is Car)
    {
        Car auto = (Car)item;
        autos.Add(auto);
        listBoxBedrijf.Items.Add(auto);
        auto.NieuweLocatieEvent += updateLocatie;
    }
    else if (item is Truck)
    {
        Truck bestel = (Truck)item;
        bestelwagens.Add(bestel);
        listBoxBedrijf.Items.Add(bestel);
        bestel.NieuweLocatieEvent += updateLocatie;
    }
    else
    {
        Person persoon = (Person)item;
        personeelsleden.Add(persoon);
        listBoxBedrijf.Items.Add(persoon);
        persoon.NieuweLocatieEvent += updateLocatie;
    }
}

To something like this:

private void makeNewItem(IMovingObject item)
{
    if (item is Car)
    {
        Car itemConverted = (Car)item;
        autos.Add(itemConverted);

    }
    else if (item is Truck)
    {
        Truck itemConverted = (Truck)item;
        bestelwagens.Add(itemConverted);
    }
    else
    {
        Person itemConverted = (Person)item;
        personeelsleden.Add(itemConverted);
    }

    listBoxBedrijf.Items.Add(itemConverted);
    itemConverted.NieuweLocatieEvent += updateLocatie;
}

But the problem is that the itemConverted is not available outside of the control structure scope, even if I change the last else if to else, so the variable would always exist.

When I create a Object itemConverted = null; in the beginning, the last code isn't aware of the methods that the concrete objects have (due to the shared interface).

I'd appreciate some advice on how to do this properly. I have not so much experience with object casting.

Aucun commentaire:

Enregistrer un commentaire