class Base
{
virtual public void FuncA()
{
MessageBox.Show("10");
}
}
public class BasePlusOne: Base
{
public void Bp1MEthod()
{
MessageBox.Show("BasePlusOne");
}
override public void FuncA()
{
MessageBox.Show("overridden by BasePlusTwo");
}
}
public class BasePlusTwo : Base
{
public void Bp1MEthod()
{
MessageBox.Show("BasePlusTwo");
}
override public void FuncA()
{
MessageBox.Show("overridden by BasePlusTwo");
}
}
public class One
{
public Base GetBase(int i )
{
if (i == 1)
{
return new BasePlusOne();
}
else
{
return new BasePlusTwo();
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
One one = new One();
Base bp =one.GetBase(2);
BasePlusOne b = (BasePlusOne)bp;
b.Bp1MEthod();
b.FuncA();
}
}
正如所见,我正在使用以下代码来动态选择base
类。我正在将base
收到的课程转换为适当的课程。如果返回的类是 ,此代码将抛出异常BasePlusOne
。有没有更好的方法来处理这种情况?这种方法还有其他错误吗?
One one = new One();
Base bp =one.GetBase(2);
BasePlusOne b = (BasePlusOne)bp;
b.Bp1MEthod();
b.FuncA();