不能对匿名方法使用use ref out参数

本文关键字:use ref out 参数 方法 不能 | 更新日期: 2023-09-27 18:05:54

    static BackgroundWorker worker; 
    static void Main(string[] args) 
    { 
      worker = new BackgroundWorker();
      worker.DoWork += worker_DoWork; 
      worker.RunWorkerAsync();
      Console.ReadLine(); 
    } 
    static void worker_DoWork(object sender,DoWorkEventArgs e) 
    { 
      string strClientId = "2211"; Authenticate(ref strClientId); 
    }
    static void Authenticate(ref string strClientId) 
    {
       Timer timer = new Timer(500); 
       //Error in this line 
       //Cannot use ref or out parameter 'strClientId' inside an anonymous method,lambda expression or query expression
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientId); 
       //timer.Elapsed += Authenticates_Timer();
       timer.Start(); 
    } 
    static void Authenticates_Timer(object sender, ElapsedEventArgs e, ref string strClientId)
    { 
      //want to use variable here 
      strClientId = "";
    }

如果有一种方法,我可以使用ref变量,而传递不能使用refor out参数'strClientId'在匿名方法、lambda表达式或查询中表达式。我知道这是一个重复的问题,但我不能弄清楚如何解决这个问题有不同的帖子和参考在代码项目张贴问题,但没有人回应任何

不能对匿名方法使用use ref out参数

我建议将strClientId作为静态变量共享:

static BackgroundWorker worker; 
static string strClientId;
static void Main(string[] args) 
{ 
  worker = new BackgroundWorker();
  worker.DoWork += worker_DoWork; 
  worker.RunWorkerAsync();
  Console.ReadLine(); 
} 
static void worker_DoWork(object sender,DoWorkEventArgs e) 
{ 
  strClientId = "2211";
  Authenticate(); 
}
static void Authenticate() 
{
   Timer timer = new Timer(500); 
   timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e); 
   timer.Start(); 
} 
static void Authenticates_Timer(object sender, ElapsedEventArgs e)
{ 
  strClientId = "";
}

对你有用吗?

更新:好的,让我们试试这个:

static void worker_DoWork(object sender,DoWorkEventArgs e) 
{ 
  string strClientId = "";
  var setClientId = new Action<string>(v => { strClientId = v; });
  setClientId("2211");
  Authenticate(setClientId); 
}
static void Authenticate(Action<string> setClientId) 
{
  Timer timer = new Timer(500); 
  timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e, setClientId); 
  timer.Start();    
}
static void Authenticates_Timer(object sender, ElapsedEventArgs e, Action<string> setClientId)
{ 
  setClientId("");
}

就这么简单:

static void Authenticate(ref string strClientId) 
{
       Timer timer = new Timer(500); 
       var strClientIdVar = strClientId;
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientIdVar);
       timer.Start(); 
}