C#对象初始化程序在做什么? [英] What am I doing wrong with C# object initializers?

查看:54
本文介绍了C#对象初始化程序在做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用C#中的新对象初始化程序初始化对象时,我无法使用该类中的属性之一执行进一步的操作,而且我也不知道为什么.

When i initialize an object using the new object initializers in C# I cannot use one of the properties within the class to perform a further action and I do not know why.

我的示例代码:

Person person = new Person { Name = "David", Age = "29" };

在Person类中,x等于0(默认值):

Within the Person Class, x will equal 0 (default):

public Person()
{
  int x = Age; // x remains 0 - edit age should be Age. This was a typo
}

但是person.Age等于29.我确定这是正常的,但我想了解原因.

However person.Age does equal 29. I am sure this is normal, but I would like to understand why.

推荐答案

在构造函数"public Person()"完成运行后,将为名称"和年龄"设置属性.

The properties get set for Name and Age after the constructor 'public Person()' has finished running.

Person person = new Person { Name = "David", Age = "29" };

等同于

Person tempPerson = new Person()
tempPerson.Name = "David";
tempPerson.Age = "29";
Person person = tempPerson;

因此,在构造函数中,年龄还不会变成29岁.

So, in the constructor Age won't have become 29 yet.

(tempPerson是您在代码中看不到的唯一变量名称,不会与以此方式构造的其他Person实例冲突.tempPerson是避免多线程问题所必需的;它的使用可确保新对象不会在构造函数执行完并且所有属性都初始化之后,其他线程才可用.)

(tempPerson is a unique variable name you don't see in your code that won't clash with other Person instances constructed in this way. tempPerson is necessary to avoid multi-threading issues; its use ensures that the new object doesn't become available to any other thread until after the constructor has been executed and after all of the properties have been initialized.)

如果您希望能够在构造函数中操作Age属性,那么我建议您创建一个以age作为参数的构造函数:

If you want to be able to manipulate the Age property in the constructor, then I suggest you create a constructor that takes the age as an argument:

public Person(string name, int age)
{
   Name = name;
   Age = age;

   // Now do something with Age
   int x = Age;
   // ...
}

这篇关于C#对象初始化程序在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆