6

在编译我的程序时(我从 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();
4

3 回答 3

8

delegate { ... }是一个匿名方法,可以分配给任何委托类型,包括ThreadStartand ParameterizedThreadStart。由于 Thread 类提供了具有两种参数类型的构造函数重载,因此构造函数重载的含义是模棱两可的。

delegate() { ... }(注意括号)是一个不带参数的匿名方法。它只能分配给不带参数委托类型,例如Actionor ThreadStart

因此,将您的代码更改为

Thread thread = new Thread(delegate() {

如果你想使用ThreadStart构造函数重载,或者

Thread thread = new Thread(delegate(object state) {

如果你想使用ParameterizedThreadStart构造函数重载。

于 2013-02-16T13:23:48.240 回答
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);
});
于 2013-02-16T13:21:12.297 回答
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();        
于 2013-02-16T13:22:33.920 回答