我已经在Die类中初始化了一个对象'_currDie',运行了一个if语句将该对象改为派生类对象,然后运行一个方法。从派生回复到基类
问题是,当它离开if语句时,它似乎正在恢复到基类。
namespace CharacterSheet
{
public partial class DiceRoller : Form
{
Die _currDie;
public DiceRoller()
{
InitializeComponent();
}
private void chooseSides_SelectedIndexChanged(object sender, EventArgs e)
{
if (chooseSides.SelectedItem.ToString() == "D4")
{
D4 _currDie = new D4();
}
if (chooseSides.SelectedItem.ToString() == "D6")
{
D6 _currDie = new D6();
}
if (chooseSides.SelectedItem.ToString() == "D8")
{
D8 _currDie = new D8();
}
if (chooseSides.SelectedItem.ToString() == "D10")
{
D10 _currDie = new D10();
}
if (chooseSides.SelectedItem.ToString() == "D20")
{
D20 _currDie = new D20();
}
if (chooseSides.SelectedItem.ToString() == "Percentile")
{
Percentile _currDie = new Percentile();
}
}
private void Roll_Click(object sender, EventArgs e)
{
_currDie.Roll();
string currResult = Convert.ToString(_currDie.RollResult);
MessageBox.Show(currResult);
}
}
}
这是基础类
namespace CharacterSheet
{
public class Die
{
public int Sides { get; set; }
private Random rng = new Random();
public int rollResult;
public int RollResult
{
get
{
return rollResult;
}
}
public virtual void Roll()
{
rollResult = rng.Next(Sides) + 1;
}
}
}
,衍生类我一直在
namespace CharacterSheet
{
public class D4:Die
{
public D4()
{
Sides = 4;
}
}
}
测试我设置为第一if语句,当我通过一步突破点_currDie.Roll();我可以清楚地看到_currDie从D4对象更改为Die对象。 在哪一点我得到一个System.NullReferenceException
我试过实例化_currDie没有定义类,但然后该方法获取错误,因为没有Roll对象的方法。
你输入得太快我放弃 –
我最初尝试了一个switch语句,但遇到了类似的异常。现在我知道问题是声明一个新的局部变量,我会再试一次。谢谢! –