C#:空传递给重载的方法 - 这方法被调用? [英] C#: Passing null to overloaded method - which method is called?

查看:85
本文介绍了C#:空传递给重载的方法 - 这方法被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个C#方法的两个重载版本:

Say I have two overloaded versions of a C# method:

void Method( TypeA a ) { }
void Method( TypeB b ) { }

我打电话的方法:

I call the method with:

Method( null );

该方法的哪一个重载叫什么名字?我能做些什么,以确保特定超载被称为?

Which overload of the method is called? What can I do to ensure that a particular overload is called?

推荐答案

这取决于类型A 的TypeB


  • 如果其中只有一个是应用(例如没有从转换为的TypeB ,因为它是一个值类型,但类型A 是引用类型),那么呼叫将被适用的一种制成。

  • 否则这取决于类型A 的TypeB 之间的关系。

    • 如果有来自类型A 的TypeB 的隐式转换但是从的隐式转换的TypeB 类型A 然后使用过载类型A 将被使用。

    • 如果有来自的TypeB 类型A 的隐式转换但是从的隐式转换类型A 的TypeB 然后使用过载的TypeB 将被使用。

    • 否则,调用是不明确的,将编译失败。

    • If exactly one of them is applicable (e.g. there is no conversion from null to TypeB because it's a value type but TypeA is a reference type) then the call will be made to the applicable one.
    • Otherwise it depends on the relationship between TypeA and TypeB.
      • If there is an implicit conversion from TypeA to TypeB but no implicit conversion from TypeB to TypeA then the overload using TypeA will be used.
      • If there is an implicit conversion from TypeB to TypeA but no implicit conversion from TypeA to TypeB then the overload using TypeB will be used.
      • Otherwise, the call is ambiguous and will fail to compile.

      查看C#3.0规范第7.4.3.4的详细规则。

      See section 7.4.3.4 of the C# 3.0 spec for the detailed rules.

      下面是它不是模棱两可的例子。在这里,的TypeB 类型A 派生,这意味着有一个从的TypeB 类型A ,而不是相反。因此,使用过载的TypeB 时:

      Here's an example of it not being ambiguous. Here TypeB derives from TypeA, which means there's an implicit conversion from TypeB to TypeA, but not vice versa. Thus the overload using TypeB is used:

      using System;
      
      class TypeA {}
      class TypeB : TypeA {}
      
      class Program
      {
          static void Foo(TypeA x)
          {
              Console.WriteLine("Foo(TypeA)");
          }
      
          static void Foo(TypeB x)
          {
              Console.WriteLine("Foo(TypeB)");
          }
      
          static void Main()
          {
              Foo(null); // Prints Foo(TypeB)
          }
      }
      

      在一般情况下,即使是在一个否则歧义呼叫的面,以保证一个特定的过载时,只是投

      In general, even in the face of an otherwise-ambiguous call, to ensure that a particular overload is used, just cast:

      Foo((TypeA) null);
      

      Foo((TypeB) null);
      

      请注意,如果这涉及在声明类继承(也就是一个类是超载其基类中声明的方法),你到完全是另外一个问题,你需要转换的方法的目标,而不是争论

      Note that if this involves inheritance in the declaring classes (i.e. one class is overloading a method declared by its base class) you're into a whole other problem, and you need to cast the target of the method rather than the argument.

      这篇关于C#:空传递给重载的方法 - 这方法被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆