相关疑难解决方法(0)

使用对象初始值设定项时,为什么编译器会生成额外的局部变量?

在昨天回答关于SO的问题时,我注意到如果使用Object Initializer初始化对象,编译器会创建一个额外的局部变量.

考虑以下在VS2008中以发布模式编译的C#3.0代码:

public class Class1
{
    public string Foo { get; set; }
}

public class Class2
{
    public string Foo { get; set; }
}

public class TestHarness
{
    static void Main(string[] args)
    {
        Class1 class1 = new Class1();
        class1.Foo = "fooBar";

        Class2 class2 =
            new Class2
            {
                Foo = "fooBar2"
            };

        Console.WriteLine(class1.Foo);
        Console.WriteLine(class2.Foo);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Reflector,我们可以检查Main方法的代码:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 2
    .locals init (
        [0] class ClassLibrary1.Class1 class1,
        [1] …
Run Code Online (Sandbox Code Playgroud)

.net c# c#-3.0

33
推荐指数
2
解决办法
1635
查看次数

标签 统计

.net ×1

c# ×1

c#-3.0 ×1