简体   繁体   English

在 C# 中的实例化期间将参数传递到大括号中的 object

[英]Passing a parameter into an object in curly brackets during instantiation in C#

When you pass an variable into an object during instantiation, such as in在实例化期间将变量传递给 object 时,例如在

SomeObject newObject = new SomeObject() { SomeString = "String goes here" };

Will the variable SomeString be accessible in the constructor or will it be assigned afterwards?变量 SomeString 可以在构造函数中访问还是之后会被分配? If I needed to use it in the constructor, would it work or would I need to pass it through as a parameter using如果我需要在构造函数中使用它,它会工作还是我需要使用它作为参数传递它

new SomeObject("String goes here");

will the variable SomeString be accessible in the constructor, or will it be assigned afterwards?变量 SomeString 是否可以在构造函数中访问,还是会在之后分配?

It will be assigned afterwards.之后会分配。

SomeObject newObject = new SomeObject() { SomeString = "String goes here" };

is roughly equivalent/syntactic sugar to:大致相当于/语法糖:

SomeObject temp = new SomeObject();
temp.SomeString = "String goes here";
SomeObject newObject = temp;

It will be assigned afterwards in the first case.它将在第一种情况下分配。 NOTE: This requires there to be a parameterless constructor , which will exist by default, unless you define a parameterized constructor.注意:这需要有一个无参数的构造函数,它默认存在,除非你定义了一个参数化的构造函数。 In that case you must define both constructors explicitly.在这种情况下,您必须明确定义这两个构造函数。

For more detail you can look at details on Object Initializers .有关更多详细信息,您可以查看Object Initializers上的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM