var如何知道未定义的类型?

Fat*_*ert 6 c# syntax

隐式类型变量如何var知道范围内未定义的类型(使用using)?

例:

还行吧

public class MyClass
{
    public void MyMethod        
    {
        var list = AStaticClass.GetList();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不行

public class MyClass
{
    public void MyMethod        
    {
        List<string> list = AStaticClass.GetList();
    }
}
Run Code Online (Sandbox Code Playgroud)

在最后一段代码中,我必须添加using System.Collections.Generic;它才能正常工作.

这是如何运作的?

Dar*_*rov 11

这是如何运作的?

当编译器的类型推断它替换varSystem.Collections.Generic.List<string>并且代码:

public class MyClass
{
    public void MyMethod        
    {
        System.Collections.Generic.List<string> list = AStaticClass.GetList();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是由于编译器吐出IL,所以下面的C#程序(没有任何using语句):

public class Program
{
    static void Main()
    {
        var result = GetList();
    }

    static System.Collections.Generic.List<string> GetList()
    {
        return new System.Collections.Generic.List<string>();
    }
}
Run Code Online (Sandbox Code Playgroud)

这个Main方法看起来像这样:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 8
    L_0000: call class [mscorlib]System.Collections.Generic.List`1<string> Program::GetList()
    L_0005: pop 
    L_0006: ret 
}
Run Code Online (Sandbox Code Playgroud)

如您所见,编译器从赋值运算符的右侧推断出类型,并替换var为完全限定的类型名称.