开发者

C# - Why doesn't constructor write the initialized value?

开发者 https://www.devze.com 2023-03-10 19:56 出处:网络
Why does\'t this code output the value of 50? class Program { static void M开发者_JAVA技巧ain(string[] args)

Why does't this code output the value of 50?

class Program
{
    static void M开发者_JAVA技巧ain(string[] args)
    {
        var myClass = new TestConstructor() { MyInt = 50 };
    }
}

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

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


This code:

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

is effectively transformed into:

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

How would you expect the property to be set before the constructor was executed?

(The use of a temporary variable here isn't important in this case, but it can be in other cases:

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

In the second line, it's important that myClass.MyInt still refers to the first object, not the newly-created one.)


That piece of code first constructs the class, and then assigns 50 to the MyInt property, after the Console.WriteLine has been executed.


Your use of the object initializer essentially translates to this:

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

The property is being set after the constructor is done. If you want to ensure the property is set in the constructor you'll need to provide a constructor that accepts a parameter:

public TestConstructor(int myInt)
{
    MyInt = myInt;
    Console.WriteLine(MyInt);
}

Using it in the following manner would display the provided integer to the console window:

var myClass = new TestConstructor(50);


Your code is translated as

 var myClass = new TestConstructor(); //Here occures Console.Write(). myInt is 0 now
 myClass.MyInt = 50;


Because the syntax you use first creates the object and calls the constructor and then sets your value.


You are calling new TestConstructor() and only in a second time you sat the property!


When using an object initializer like you are using, the default constructor is called first and THEN the various properties and fields you are setting are set.

This means that you're probably seeing the value of default(int) in the console here, since you don't set the value in the constructor itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消