当我使用C#中的新对象初始化器初始化对象时,我不能使用类中的一个属性来执行进一步的操作,我不知道为什么.
我的示例代码:
Person person = new Person { Name = "David", Age = "29" };
在Person类中,x将等于0(默认值):
public Person() { int x = Age; // x remains 0 - edit age should be Age. This was a typo }
然而,person.Age确实等于29.我确信这是正常的,但我想明白为什么.
在构造函数'public Person()'运行完毕后,为Name和Age设置属性.
Person person = new Person { Name = "David", Age = "29" };
相当于
Person tempPerson = new Person() tempPerson.Name = "David"; tempPerson.Age = "29"; Person person = tempPerson;
所以,在构造函数中,Age还不会变成29.
(tempPerson是一个你在代码中看不到的唯一变量名,它不会与以这种方式构造的其他Person实例冲突.tempPerson是避免多线程问题所必需的;它的使用确保新对象不会成为可用于任何其他线程,直到构造函数执行完毕并且所有属性都已初始化之后.)
如果您希望能够在构造函数中操作Age属性,那么我建议您创建一个以年龄为参数的构造函数:
public Person(string name, int age) { Name = name; Age = age; // Now do something with Age int x = Age; // ... }
请注意,作为重要的技术细节,:
Person person = new Person { Name = "David", Age = "29" };
相当于:
Person <>0 = new Person(); // a local variable which is not visible within C# <>0.Name = "David"; <>0.Age = "29"; Person person = <>0;
但不等同于:
Person person = new Person(); person.Name = "David"; person.Age = "29";
您的代码行与以下内容相同:
Person person = new Person() { Name = "David", Age = "29" };
这与:
Person person = new Person(); person.Name = "David"; person.Age = "29";
如你看到的; 当构造函数执行时,Age
尚未设置.