简体   繁体   中英

How can I pass an instance of a basetype and then check what kind of subtype it is?

I've got a base class and three subtypes that derive from that class (see example below).

public abstract class Vehicle
{
    string name;
    string color;
}

public class Car : Vehicle 
{
    int nrofwheels;
}
public class Train : Vehicle 
{
    int nrofrailcars;
}

To make one of my method as generic as possible, I'd like to pass the base type as parameter and then detect hat subtype it is inside my method like this:

public static void main(string[] args)
{
    public Car c = new Car();
    public Train t = new Train();

    public CheckType(Vehicle v)
    {
        if(v.GetType()==typeof(Car)) Console.Write(v.nrofwheels);
        else Console.Write(v.nrofrailcars);
    }
}

This doesn't seem to work, why and what else can I try?

[edit] I know that the class examples aren't complete, but I'd figured that its not necessary for this purpose.

You should refactor that class and move CheckType to Vehicle class and override it in descendant classes. And CheckType name is not the best one, it makes no sense since that method returns number of wheels / rails.

Something like this:

public abstract class Vehicle
{
    string name;
    string color;

    public abstract int CheckType();
}

public class Car : Vehicle 
{
    int nrofwheels;
    public override int CheckType()
    {
        return this.nrofwheels;
    }
}

public class Train : Vehicle 
{
    int nrofrailcars;
    public override int CheckType()
    {
        return this.nrofrailcars;
    }
}

You can use as . You forgot to cast the object to make the properties accessible:

public CheckType(Vehicle v)
{
    Train t = v as Train;

    if (t != null)
        Console.Write(t.nrofrailcars);
    else
    {
        Car c = v as Car;

        if (c != null)
            Console.Write(c.nrofwheels);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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