我对 C# 对象初始值设定项做错了什么?

发布于 2024-07-13 23:26:57 字数 363 浏览 10 评论 0原文

当我使用 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。我确信这是正常的,但我想了解原因。

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.

My example code:

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

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
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

緦唸λ蓇 2024-07-20 23:26:57

构造函数“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;

So,在构造函数中 Age 还不会变成 29。

(tempPerson 是您在代码中看不到的唯一变量名,它不会与以这种方式构造的其他 Person 实例冲突。tempPerson 对于避免多线程问题是必要的;它的使用确保新对象不会成为在执行构造函数和初始化所有属性之后,任何其他线程都可以使用它。)


如果您希望能够在构造函数中操作 Age 属性,那么我建议您创建一个将年龄作为一个论点:

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

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

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

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

is equivalent to

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

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

(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.)


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;
   // ...
}
沫尐诺 2024-07-20 23:26:57

请注意,作为一个重要的技术细节,:

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";

Note, as an important technical detail, that:

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

is equivalent to:

Person <>0 = new Person(); // a local variable which is not visible within C#
<>0.Name = "David";
<>0.Age = "29";
Person person = <>0;

but is not equivalent to:

Person person = new Person();
person.Name = "David";
person.Age = "29";
丿*梦醉红颜 2024-07-20 23:26:57

您的代码行与:

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

相同,与:

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

如您所见; 当构造函数执行时,Age 尚未设置。

Your line of code is identical to:

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

which is identical to:

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

As you can see; when the constructor executes, Age is not yet set.

风柔一江水 2024-07-20 23:26:57

从技术上讲,此代码:

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

与此代码相同:

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

与其他人发布的代码略有不同:

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

如果您的应用程序使用多线程,则这种差异至关重要。

Technically, this code:

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

is identical to this code:

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

which is slightly different than what others have posted:

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

This difference is crucial if your application is using multi-threading.

东京女 2024-07-20 23:26:57

看起来您正在尝试在对象的构造函数中访问 Age 。 在构造函数执行之后才会设置对象初始值设定项值。

试试这个:

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

编辑响应评论

如果您需要在构造函数本身中访问Age,那么您需要使用所需参数创建一个显式构造函数,并使用它而不是对象初始值设定项语法。 例如:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

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

        int x = Age;  // will be 29 in this example
    }
}

Person person = new Person("David", 29);

It looks like you're trying to access Age in the object's constructor. The object initializer values won't be set until after the constructor has executed.

Try this:

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

EDIT in response to comment

If you need access to Age in the constructor itself then you'll need to create an explicit constructor with the required parameters, and use that instead of the object initializer syntax. For example:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

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

        int x = Age;  // will be 29 in this example
    }
}

Person person = new Person("David", 29);
倥絔 2024-07-20 23:26:57

好吧,正如其他人所说,无参数构造函数首先被执行,因此你陷入了困境。

但是,我确实要问,您是否为 Age 变量设置了一个字段而不是自动属性?

public class Person
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
 }

如果足够,或者如果您确实需要使用 x,您可以使用 _age 而不是 x

public class Person
{
    private int _age;
    private int x;

    public int Age
    {
        get { return _age; }
        set 
        { 
            _age = value;
            x = _age;
        }
    }
 }

以更合适的为准。

Well, as others said, the parameterless constructor got executed first, hence your quandary.

I do have to ask however, if you've set a field instead of an automatic property for your Age variable?

public class Person
{
    private int _age;

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
 }

You could use _age instead of x if that's enough, or if you really need to use x:

public class Person
{
    private int _age;
    private int x;

    public int Age
    {
        get { return _age; }
        set 
        { 
            _age = value;
            x = _age;
        }
    }
 }

Whichever is more appropriate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文