你好,我刚学C#,有个小问题学请教一下,我想在窗口类里面修改另外一个类中的属性(控制定时器时间间隔的值)。修改后我在窗口类里面显示出来是修改成功了,但是在另外那个类本身的属性值没有被成功修改我百度好久了。希望大家指点下。

解决方案 »

  1.   

    static class Global
    {
        public static A a = new A();
        public static B b = new B();
    }class A
    {
        public void foo()
        {
            Global.b.Interval = 100;
        }
    }class B
    {
        public int Interval { get; set; }
    }
      

  2.   

    代码大概是这样的:
    我在一个类中创建了一个定时器        public System.Timers.Timer timerBlock;//定时器
            public int _timeSpen = 800;//定时器时间间隔
            public int TimeSpen
            {
                set { _timeSpen = value; }
                get { return _timeSpen; }
            }
     //初始化定时器
                timerBlock = new System.Timers.Timer(_timeSpen);
                timerBlock.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
                timerBlock.AutoReset = true;
                timerBlock.Start();        private void OnTimedEvent(object source,ElapsedEventArgs e){
                //实现了部分功能的代码
            } 然后先想在另一个类(主窗口)通过一个按钮去改变定时器的时间间隔
            private void button1_Click(object sender, EventArgs e)
            {
                p.TimeSpen = 200;
            } 
     
    后面再运行初始化的这段代码
    timerBlock = new System.Timers.Timer(_timeSpen);
                timerBlock.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
                timerBlock.AutoReset = true;
                timerBlock.Start();
    但是_timeSpen的值还是800,没有变为200
      

  3.   

    代码看起来是没什么文替的不过我觉得没必要高的这么复杂
    TimeSpen应该这么写:
     public int TimeSpen
      {
      set { timerBlock.Interval = value; }
      get { return timerBlock.Interval; }
      }
    _timeSpen没有存在的价值
    另外那个单词应该是TimeSpan吧
      

  4.   

    把你的TimeSpen设置为static试试,不过定时器在运行的时候修改timespan过后能立即生效么?这个我没验证过