繁体   English   中英

C#新手,关于控制在构造函数中创建的定时器的问题

[英]C# novice, question about controlling timers created in a constructor

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

计时器正是我需要它做的,但我也希望能够使用.Stop(); 和.Start(); 从主程序。

不止于此,但这足以重现我的确切问题。

在下面的示例中,我可以访问 Monsters[index].M_timer but.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;
        }
    }

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

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

该死的,我应该再给这个几分钟:

公共对象 M_timer;

替换为

公共定时器 M_timer;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM