【问题标题】:How to resolve ambiguity when argument is null?当参数为空时如何解决歧义?
【发布时间】:2010-10-28 14:52:33
【问题描述】:

编译以下代码将返回The call is ambiguous between the following methods or properties 错误。由于我无法将 null 显式转换为任何这些类,如何解决它?

static void Main(string[] args)
{
    Func(null);
}

void Func(Class1 a)
{

}

void Func(Class2 b)
{

}

【问题讨论】:

  • 哦,抱歉,看来我可以了 :)

标签: c# null ambiguous-call


【解决方案1】:
Func((Class1)null);

【讨论】:

    【解决方案2】:

    使用as 进行强制转换使其在具有相同功能的情况下更具可读性。

    Func(null as Class1);
    

    【讨论】:

      【解决方案3】:

      你也可以使用变量:

      Class1 x = null;
      Func(x);
      

      【讨论】:

      • +1 这种方法比 func((Class1)null) 更容易阅读和理解。强制转换 null 并不直观。
      • 这比尽可能进行强制转换更可取,因为它会在编译时捕获许多问题,否则会出现运行时强制转换错误。
      【解决方案4】:

      只是我更喜欢的替代解决方案

      static void Main(string[] args)
      {
          Func(Class1.NULL);
      }
      
      void Func(Class1 a)
      { }
      
      void Func(Class2 b)
      { }
      
      class Class1
      {
          public static readonly Class1 NULL = null;
      }
      
      class Class2
      {
          public static readonly Class2 NULL = null;
      }
      

      【讨论】:

        【解决方案5】:

        null 转换为类型:

        Func((Class1)null);
        

        【讨论】:

          【解决方案6】:

          Func() 方法接受引用类型作为参数,该参数可以为 null。由于您使用显式 null 值调用该方法,因此编译器不知道您的 null 是否应该引用 Class1 对象或 Class2 对象。

          你有两个选择:

          将 null 转换为 Class1Class2 类型,如 Func((Class1)null)Func((Class2)null)

          提供不接受参数的Func() 方法的新重载,并在没有显式对象引用时调用该重载:

          void Func()
          {
              // call this when no object is available
          }
          

          【讨论】:

            【解决方案7】:

            您应该能够将 null 转换为其中任何一个,就像您将变量 Func((Class1)null) 转换为一样。

            【讨论】:

              猜你喜欢
              • 2011-05-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-08-16
              • 2017-10-03
              • 2022-01-18
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多