【问题标题】:C# novice, question about controlling timers created in a constructorC#新手,关于控制构造函数中创建的定时器的问题
【发布时间】:2019-11-28 06:11:25
【问题描述】:

我有一个在构造函数中创建计时器的类。

计时器完全符合我的需要,但我也希望能够使用 .Stop();和 .Start();从主程序。

还有很多,但这足以重现我的确切问题。

在下面的示例中,我可以访问 Monsters[index].M_timer 但 .Stop();报错。

class Program
    {
        static void Main(string[] args)
        {
            int index = 0;
            string name = "Spider";
            monster[] Monsters = new monster[100];
            Monsters[index] = Create_Monster(name);
            /*
            Monsters[1].M_timer.Stop(); <- not how I will be using this but I need the functionality here
            */
        }
        public static monster Create_Monster(string _name)
        {
            int timer = 0;
            if (_name == "Spider")
            {
                timer = 4000;
            }
            monster build = new monster(false, timer);
            return build;
        }
    }
class monster
    {
        public bool can_act;
        public int _timer;
        public object M_timer;

        public monster(bool _can_act, int _timer)
        {
            can_act = _can_act;
            Timer M_timer = new Timer();
            M_timer.Interval = _timer;
            M_timer.AutoReset = true;
            M_timer.Enabled = true;
            M_timer.Elapsed += TimerEvent;
        }
        public void TimerEvent(object source, ElapsedEventArgs e)
        {
            can_act = true;
        }
    }

【问题讨论】:

  • 你能在这个问题中添加错误信息吗?
  • 还有什么样的定时器?你不需要秒表吗?定时器来自 System.Threading?
  • 它是一个计时器,用于记录怪物在获得行动能力之前的睡眠时间。一旦动作发生,can_act 的标志就会回到 false,直到时间再次过去。启动/停止功能用于如果我想暂停怪物或者如果他们死了我需要能够处理计时器。我让它工作了。错误是在主程序中将计时器称为通用对象而不是实际计时器,这是我没有看到的愚蠢错误。

标签: c# constructor timer


【解决方案1】:

乍一看,您似乎有几个问题。首先,是范围。您的构造函数中有一个名为 M_timer 的变量,它涵盖了类字段 M_timer。您在这里没有对相同的对象进行操作。你必须说类似this.M_timer = M_timer.

第二个问题是当你想使用它时你必须强制转换类字段,因为它是一个通用对象。所以你必须说类似((Timer)Monsters[1].M_timer).Stop()

【讨论】:

    【解决方案2】:

    该死,我应该再等几分钟:

    公共对象M_timer;

    替换为

    公共定时器 M_timer;

    【讨论】:

    • 这解决了您的一个问题,但请记住,在构造函数中您正在使用不同的计时器。您创建 2 个具有相同名称的变量。由于作用域的工作方式,它作用于内部变量并忽略具有相同名称的外部变量。为清楚起见,最好 a) 只使用您创建的公共计时器,或者使用不同的名称并将类计时器分配给构造函数的计时器:this.M_timer = mtimer
    • 不太担心命名约定。我退休了,这样做只是为了我自己和乐趣。尽管我非常关心学习这一切是如何工作的,而且你们到目前为止都很棒(我可能已经阅读了 100 个线程来自己解决问题)。
    • 这不是命名约定的问题,只是因为它们是不同的对象,您可能会遇到意外行为。如果您有任何其他问题,请随时提出,尽管
    • 我确实做到了。我看到没有 .Pause();如果我想执行以下操作: X= 定时器 timer.Stop() 的当前值; timer.Interval =X timer.Start();实际的语法是什么?
    • 你想从中断的地方继续吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多