【问题标题】:The call is ambiguous between the following methods or properties C#以下方法或属性 C# 之间的调用不明确
【发布时间】:2013-02-16 13:17:32
【问题描述】:

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

【问题讨论】:

    标签: c# monodevelop ambiguous


    【解决方案1】:

    delegate { ... } 是一个匿名方法,可以分配给any 委托类型,包括ThreadStartParameterizedThreadStart。由于 Thread 类为这两种参数类型都提供了构造函数重载,因此不明确是指哪个构造函数重载。

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

    所以,把你的代码改成

    Thread thread = new Thread(delegate() {
    

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

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

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

    【讨论】:

      【解决方案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);
      });
      

      【讨论】:

        【解决方案3】:

        或者,您可以使用 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();        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-09
          • 2020-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多