2013-02-16 64 views
6

雖然編譯我的程序(ⅰ編譯它從MonoDevelop的IDE)收到錯誤:呼叫是以下方法或屬性С#之間曖昧

Error CS0121: The call is ambiguous between the following methods or properties: 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(); 

感謝您的關注

回答

8

delegate { ... }是一個匿名方法,其可分配給任何委託類型,包括ThreadStartParameterizedThreadStart。由於Thread類使用兩種參數類型都提供了構造函數重載,所以構造函數重載的含義是不明確的。

delegate() { ... }(注意圓括號)是一個不帶參數的匿名方法。可以分配只有委派不帶參數的類型,例如ActionThreadStart

所以,如果你想使用ParameterizedThreadStart構造函數重載你的代碼,如果你想使用ThreadStart構造函數重載改變

Thread thread = new Thread(delegate() { 

,或者

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

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); 
}); 
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();