在编译我的程序时(我从MonoDevelop IDE编译它)我收到一个错误:
错误CS0121:以下方法或之间的调用不明确 特性:
System.Threading.Thread.Thread(System.Threading.ThreadStart)' and
System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)” (CS0121)
这是代码的一部分。
Thread thread = new Thread(delegate {
try
{
Helper.CopyFolder(from, to);
Helper.RunProgram("chown", "-R www-data:www-data " + to);
}
catch (Exception exception)
{
Helper.DeactivateThread(Thread.CurrentThread.Name);
}
Helper.DeactivateThread(Thread.CurrentThread.Name);
});
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
thread.Name = name;
thread.Start();
答案 0 :(得分:8)
delegate { ... }
是一种匿名方法,可以分配给任何委托类型,包括ThreadStart
和ParameterizedThreadStart
。由于Thread类提供了两种参数类型的构造函数重载,因此构造函数重载的含义是不明确的。
delegate() { ... }
(注意括号)是一个不带参数的匿名方法。可以指定 来委派不带参数的类型,例如Action
或ThreadStart
。
所以,将代码更改为
Thread thread = new Thread(delegate() {
如果你想使用ThreadStart
构造函数重载,或者
Thread thread = new Thread(delegate(object state) {
如果你想使用ParameterizedThreadStart
构造函数重载。
答案 1 :(得分:2)
如果您的方法具有重载并且您的使用可能与重载一起使用,则会引发此错误。编译器不确定要调用哪个重载,因此需要通过强制转换参数来明确说明它。一种方法是这样的:
Thread thread = new Thread((ThreadStart)delegate {
try
{
Helper.CopyFolder(from, to);
Helper.RunProgram("chown", "-R www-data:www-data " + to);
}
catch (Exception exception)
{
Helper.DeactivateThread(Thread.CurrentThread.Name);
}
Helper.DeactivateThread(Thread.CurrentThread.Name);
});
答案 2 :(得分:0)
或者,您可以使用lambda:
Thread thread = new Thread(() =>
{
try
{
Helper.CopyFolder(from, to);
Helper.RunProgram("chown", "-R www-data:www-data " + to);
}
catch (Exception exception)
{
Helper.DeactivateThread(Thread.CurrentThread.Name);
}
Helper.DeactivateThread(Thread.CurrentThread.Name);
});
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
thread.Name = name;
thread.Start();