The*_*ato 2 c# inheritance types
我有一个名为a的基类,它有一个名为Foo的虚函数
class a
{
public virtual void Foo() {}
}
Run Code Online (Sandbox Code Playgroud)
我还有很多继承自它的其他类.
class B : A{}
class C : A{}
class D : A{}
class E : A{}
Run Code Online (Sandbox Code Playgroud)
现在,我希望有一个类型的数组,所以我可以随机选择一个所以我试过这个:
class Boo
{
Type[] options;
public Boo()
{
options = new[]
{
typeof(B),
typeof(C),
typeof(D),
typeof(E)
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后我想随机选择一个并使用它的Foo方法,我这样做:
Random rnd = new Random();
(options[rnd.Next(options.Length)] as A).Foo()
Run Code Online (Sandbox Code Playgroud)
但这不起作用,有没有办法实现这一点?
(顺便说一句,我没有这个名字,所以如果有人有更好的名字,他们可以随意编辑:))
options应该是一个A实例数组,而不是一个Type[].
class Boo {
public A[] options;
public Boo() {
options = new[] {
new B(),
new C(),
new D(),
new E()
};
}
}
Run Code Online (Sandbox Code Playgroud)