将变量作为参数传递给类,并在该类的方法中更改该变量的值

本文关键字:变量 方法 参数传递 | 更新日期: 2023-09-27 18:06:41

如果有错别字请原谅,我是手写的。我只是想知道是否有任何方法我可以传递一个参数给一个类,并在该变量的方法内改变它的变量。

我正在考虑通过引用传递,但我不能通过Elapsed方法属性传递变量。有什么建议吗?

public partial class MainWindow : Window
{
  private CustomTimerClass _customTimer;
  private int _varIWantToChange;
  public MainWindow()
  {
     _varIWantToChange = 1;
     _customTimer = new CustomTimerClass(_varIWantToChange);
  }
  ...
}
public CustomTimerClass()
{
  private System.Timers.Timer _timer;
  public CustomTimerClass(int varIWantToChange)
  {
    _timer = new Timer();
    ...
    _timer.Elapsed += _timer_Elapsed;  //i can't pass varIwantToChange as a parameter here
  }
  public void _timer_Elapsed(object sender, ElapsedEventArgs e)
  {
    //i want to be able to change the value of the variable "_varIWantToChange" here
  }
}

将变量作为参数传递给类,并在该类的方法中更改该变量的值

你可以很容易地传入一个回调方法:

   class Program
   {
      static private CustomTimerClass _customTimer;
      static private int _varIWantToChange = 1;
      static public void Main()
      {
         _customTimer = new CustomTimerClass(changeVar);
         while (_varIWantToChange == 1)
         {
            System.Threading.Thread.Sleep(1);
         }
      }
      static public void changeVar(object sender, ElapsedEventArgs e)
      {
         _varIWantToChange++;
         Console.WriteLine(_varIWantToChange);
      }
   }
   public class CustomTimerClass
   {
      private System.Timers.Timer _timer;
      public CustomTimerClass()
      {
      }
      public CustomTimerClass(ElapsedEventHandler callbackMethod)
      {
         _timer = new Timer();
         _timer.Elapsed += callbackMethod;  //i can't pass varIwantToChange as a parameter here
         _timer.Elapsed += _timer_Elapsed;
         _timer.Interval = 500;
         _timer.Start();
      }
      public void _timer_Elapsed(object sender, ElapsedEventArgs e)
      {
         // Do timer stuff
      }
   }

创建一个公共int属性

让你的属性设置为_varIWantToChange,并在需要时获取_varIWantToChange

你为什么不使用System.Threading.Timer而使用system . timer . timer ?Threading版本的构造函数允许您在构造函数中传递对象,然后将对象作为参数传递给处理程序。

From MSDN: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx