如何观察不同类的整数

我试图将用户输入从文本框转换为整数(在 c# 中),然后从具有该整数索引的数组中输出一个值。这是我的代码的一小部分:


 public Form1()

{

 InitializeComponent();

        string[] Cmaj = new string [7];

            Cmaj[1] = "C";

            Cmaj[2] = "D";

            Cmaj[3] = "E";

            Cmaj[4] = "F";

            Cmaj[5] = "G";

            Cmaj[6] = "A";

            Cmaj[7] = "B";



       int roman = int.Parse(textBox3.Text);

       textBox4.Text = Cmaj[roman];


}


但每次运行此命令时,我都会收到有关“int roman = int.Parse(textBox3.Text);”的错误 (下面列出)。我最初使用的是 Convert.ToInt32 而不是 int.Parse,但我看到了有关此主题的另一个问题,该问题说使用解析而不是转换。然而,这并没有太大改变。我应该怎么办?


错误:mscorlib.dll 中发生“System.FormatException”类型的未处理异常


附加信息:输入字符串的格式不正确。


白衣染霜花
浏览 136回答 3
3回答

qq_笑_17

如果无法访问 Player 类,一种选择是仅在设定的时间间隔内检查所有玩家的 Life 变量的值。您需要在 Game 类中保留局部变量,以跟踪 Life 变量之前设置的内容,但是每当您注意到 Life 变量的值之一发生更改时,您都可以在 Game 中执行您需要的任何代码类,这将为您提供与事件处理程序基本相同的行为(尽管可能不那么有效)。class Game {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; List<Player> playerList;&nbsp; &nbsp; ArrayList lifeValues;&nbsp; &nbsp; System.Timers.Timer lifeCheckTimer;&nbsp; &nbsp; Game() {&nbsp; &nbsp; &nbsp; &nbsp; playerList = new List<Player>();&nbsp; &nbsp; &nbsp; &nbsp; //add all players that have been instantiated to the above list here&nbsp; &nbsp; &nbsp; &nbsp; lifeValues = new ArrayList();&nbsp; &nbsp; &nbsp; &nbsp; //add all the player.Life values to the above list here&nbsp; &nbsp; &nbsp; &nbsp; //these will need to be added in the same order&nbsp; &nbsp; &nbsp; &nbsp; lifeCheckTimer = new System.Timers.Timer();&nbsp; &nbsp; &nbsp; &nbsp; lifeCheckTimer.Elapsed += new ElapsedEventHandler(lifeCheckElapsed);&nbsp; &nbsp; &nbsp; &nbsp; //you can change the 500 (0.5 seconds) below to whatever interval you want to&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //check for a change in players life values (in milliseconds)&nbsp; &nbsp; &nbsp; &nbsp; lifeCheckTimer.Interval = 500;&nbsp; &nbsp; &nbsp; &nbsp; lifeCheckTimer.Enabled = true;&nbsp; &nbsp; }&nbsp; &nbsp; private static void lifeCheckElapsed(object source, ElapsedEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < playerList.Count(); i ++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (((Player)playerList[i]).Life != lifeValues[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OnPlayerLifeChange();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lifeValues[i] = ((Player)playerList[i]).Life;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

慕仙森

一种常见的方法是在 Player 类中实现 INotifyPropertyChanged 接口,将 Life 从字段更改为属性,并从 setter 引发 PropertyChanged 事件。class Player : INotofyPropertyChanged{&nbsp; &nbsp; private int _life;&nbsp; &nbsp; public int Life&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return _life; }&nbsp; &nbsp; &nbsp; &nbsp; set { _life = value; OnPropertyChanged("Life"); }&nbsp; &nbsp; }&nbsp; &nbsp; ....}然后游戏可以订阅所有玩家的 PropertyChanged 事件并做出相应的反应。

ibeautiful

编写 Player 类的人需要添加一个公共方法来检查变量的任何更新Life。那么你只需要使用该方法即可。如果这个人没有编写这样的方法,那么你就无法访问它(这就是为什么封装很重要,否则任何人都可以访问不应该访问的东西)
打开App,查看更多内容
随时随地看视频慕课网APP