Skip to main content
 首页 » 编程设计

c#之为什么将 null 转换为类型以进行方法选择

2024年02月13日12qlqwjy

根据C#: Passing null to overloaded method - which method is called?的回答,空值似乎带有类型信息。其实我也可以用

class Program 
{ 
    static void Method(TypeA a) 
    { 
        Console.Write("Output of Method(TypeA a):"); 
        Console.WriteLine(a); // Prints nothing, on account of the null. 
    } 
    static void Method(TypeB b) 
    { 
        Console.Write("Output of Method(TypeB b):"); 
        Console.WriteLine(b); // Also prints nothing, on account of the null. 
    } 
    static void Main() 
    { 
        var a = (TypeA)null; 
        var b = (TypeB)null; 
        Method(a); 
        Method(b); 
    } 
} 
class TypeA { } 
class TypeB { } 

哪个产量

Output of Method(TypeA a):
Output of Method(TypeB b):

这是怎么回事?

请您参考如下方法:

不,null 本身不携带类型信息。强制转换只是告诉编译器变量a和b的类型应该是什么……没有强制转换就无法判断,因为 null 可以转换为任何引用类型或可空类型。

这些变量的类型随后用于重载决议。不要忘记这里的选择只是在编译时做出的——它根本不涉及参数的执行时值。

您的代码完全等同于:

TypeA a = null; 
TypeB b = null; 
Method(a); 
Method(b); 

如果您使用动态 类型,以便在执行时执行重载解析,您将失败:

dynamic foo = (TypeA) null; // Or without the cast. It makes no difference. 
Method(foo); // RuntimeBinderException at execution time, due to ambiguity