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变量 参数to event不能使用ref或out参数' strClientId' 在匿名方法,lambda表达式或查询中 表达。我知道这是重复的问题,但我无法做到 弄清楚如何解决这个问题已经提到了不同的帖子和 在codeproject中也发布了问题,但没有人回应任何问题 感谢帮助
答案 0 :(得分:0)
我建议将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("");
}
答案 1 :(得分:0)
就这么简单:
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();
}