C# 中对象初始化器的解释?
如果可能的话,有人可以提供 C# 中对象初始化程序的解释和示例吗?
到目前为止,我了解到它们允许您压缩类的实例,这是正确的吗?
Could someone please provide a explanation of Object Initialisers in C# and examples if possible.
So far I understand that they allow you to condense instances of a class, is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对象初始值设定项已添加到 C# 版本 3 中,并提供精简的对象初始化语法。它们只不过是语法糖,这意味着它们允许您表达比以前更短的相同代码。
这是一个示例:
相当于:
在此处查看官方 文档。
一个相关的功能是集合初始值设定项,它可以让您轻松初始化集合:
上面的代码是构造一个新列表,然后将每个元素添加到其中的简写。要使集合初始值设定项适用于某种类型,只需采用正确类型作为参数的
public Add
方法即可。Object initializers was added to C# in version 3, and provide condensed object initialization syntax. They are nothing but syntactic sugar, meaning they allow you to express the same code shorter than before.
Here is an example:
Which is the equivalent of:
Have a look on the official documentation here.
A related feature is collection initializers, which lets you initialize collections easily:
The above code is short hand for constructing a new List, and then adding each element to it. For collection initializers to work for a type, nothing more is required than a
public Add
method taking the correct type as the parameter.对象初始值设定项允许您在创建时将值分配给对象的任何可访问字段或属性,而无需显式调用构造函数。
请参阅对象和集合初始值设定项(C# 编程指南)。
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
Refer to Object and Collection Initializers (C# Programming Guide).
对象初始值设定项允许您在声明实例时设置实例的属性。例如:
然后使用这个:
在创建对象时简单地设置这些值,有点像构造函数,您可以在其中选择要设置的属性。您还可以使用构造函数:
这实际上只是语法糖,编译器将其转换为等效的 C# 代码:
Object Initialisers allow you to set the properties of an instance when you declare it. For example:
Then using this:
Simply sets these values when you create the object, a bit like a constructor where you can choose which properties to set. You can also use a constructor as well:
This is actually just syntactic sugar, the compiler converts it to this equivalent C# code:
来自 MSDN
所有这些意味着它是一个方便的快捷方式,您可以使用它(希望)使您的代码更具可读性。他们给出的例子:
更传统地写为:
或者
前者可能更冗长,并且编译后的代码之间存在差异(感谢 @Kirk Woll 获取链接),解释于 这篇文章。初始化程序创建一个临时变量,分配属性,然后将其复制到实际变量。类似这样:
后者(在带有可选参数的 C# 4.0 之前)要求您为每个可能的参数组合拥有许多重载版本的构造函数。
From the MSDN
All this means is that it's a convenient shortcut you can use to (hopefully) make your code more readable. The example they give:
would be more traditionally written as:
or
The former can be more long winded, and there is a difference between the compiled code (thanks to @Kirk Woll for the link), explained in this post. The initialiser creates a temporary variable, assigns the properties and then copies that to the real variable. Something like this:
The latter would (before C# 4.0 with optional arguments) require you to have a many overloaded versions of your constructor for each possible parameter combination.