我可以在不显式转换对象类型的情况下从对象的父类调用函数和变量吗?

时间:2018-09-16 19:44:10

标签: c# inheritance casting

我想浏览一列不同对象的列表,这些对象都是从同一父类的子类派生的,并且无论如何我只想使用父类的东西。

public class Foo{ public int a=0; }
public class Bar : foo{  }
public class Gun : foo{  }
public class Shotgun : Gun{  }
public class Rifle : Gun{  }

那我以后要做什么:

object[] Array ={new Bar(),new Shotgun(),new Rifle()};
int index=0;
foreach(SubclassOfFoo obj in (Array as SubclassOfFoo[]))
{
    (Array[index] as SubclassOfFoo).a++;
    Console.WriteLine(obj.a);

    index++;
}

希望有一些方法可以做到这一点。

2 个答案:

答案 0 :(得分:2)

我将为基类Foo而不是object创建一个集合

List<Foo> array = new List<Foo>();
array.Add(new Bar());
array.Add(new Shotgun());
array.Add(new Rifle());

那么您可以直接使用集合而无需强制转换。

foreach(Foo obj in array)
{
    Console.WriteLine(obj.a);
    index++;
}

答案 1 :(得分:2)

我建议声明父类型的数组:

Foo[] Array =new Foo{new Bar(),new Shotgun(),new Rifle()};

这种方式不需要强制转换:

foreach(Foo obj in Array))
{
    obj.a++;
    Console.WriteLine(obj.a);
}

由于所有子类都继承自FooFoo的子代,因此此数组可以容纳所有子代和孙代。 每个子类将具有属性a。无需铸造

相关问题