为什么此代码不输出值50?

class Program
{
    static void Main(string[] args)
    {
        var myClass = new TestConstructor() { MyInt = 50 };
    }
}

class TestConstructor
{
    public int MyInt { get; set; }

    public TestConstructor()
    {
        Console.WriteLine(this.MyInt);
        Console.Read();
    }
}

最佳答案

这段代码:

 var myClass = new TestConstructor() { MyInt = 50 };


有效地转换为:

var tmp = new TestConstructor();
tmp.MyInt = 50;
var myClass = tmp;


您如何期望在构造函数执行之前设置属性?

(在这种情况下,此处使用临时变量并不重要,但在其他情况下也可以:

var myClass = new TestConstructor { MyInt = 50 };
myClass = new TestConstructor { MyInt = myClass.MyInt + 2 };


在第二行中,重要的是,myClass.MyInt仍引用第一个对象,而不是新创建的对象。)

10-02 15:09
查看更多