我知道这个类的例子是不完整的,但是我认为对于这个目的来说没有必要。
我已经有了一个基类和从该类派生的三个子类型(参见下面的示例)。
public abstract class Vehicle
{
string name;
string color;
}
public class Car : Vehicle
{
int nrofwheels;
}
public class Train : Vehicle
{
int nrofrailcars;
}
为了使我的一个方法尽可能泛型,我想将基本类型作为参数传递,然后检测它在我的方法中的子类型,如下所示:
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);
}
}
这似乎不起作用,为什么,我还可以尝试什么?
您应该重构该类,并将CheckType移动到Vehicle类中,并在后代类中重写它。CheckType名称不是最好的,它没有意义,因为该方法返回车轮/轨道的数量。
像这样:
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;
}
}
您可以使用as
。您忘记强制转换对象以使属性可访问:
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);
}
}