gpt4 book ai didi

c# - new() 之后的括号是否存在名称?

转载 作者:行者123 更新时间:2023-11-30 13:26:24 25 4
gpt4 key购买 nike

我想详细了解我偶尔在某些 C# 代码中看到的结构;但是,我不知道名字。如果这是重复的,我深表歉意;然而,如果不知道它们的名字就很难搜索它们。

构造如下:

Person me = new Person(){ Name = "Aelphaeis" } ;

像这样分配字段/属性有专门的名称吗?

最佳答案

这称为对象初始化器。例如,我们有一个名为 Customer 的类,其定义如下:

public class Customer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

然后你可以像下面这样实例化一个 Customer 类型的对象:

Customer customer = new Customer 
{
ID = 0,
FirstName="firstName",
LastName="lastName",
Age = 20
};

简而言之,这是实例化对象的另一种方式。

What happens behind the scenes, when we use an object initializer?

调用 Customer 的默认空构造函数:

Customer customer = new Customer();

然后属性的 setter 被调用,按照它们在对象初始值设定项中写入的顺序:

customer.ID = 0;
customer.FirstName = "firstName";
customer.LastName = "lastName";
customer.Age = 20;

此外,一个接近对象初始化器的概念是集合初始化器

而不是这样写:

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);

我们可以这样写:

List<int> numbers = new List<int>() { 1, 2, 3, 4 };

这绝对比初始版本更紧凑,我想说也更具表现力。在上面的示例中,我们使用了一个集合初始化器

What happens behind the scenes, when we use a collection initializer?

如果我们以最后一个例子为例,它就是这样发生的:

// Create the a new list
List<int> numbers = new List<int>();

// Add one element after the other, in the order they appear in the
// collection initializer, using the Add method.
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);

有关对象和集合初始值设定项的更多信息,请访问此link .

最后但同样重要的是,我想指出 对象和集合初始值设定项 是在 C# 3.0 中引入的。不幸的是,如果您必须在 C# 2.0 时代编写应用程序,那么您将无法使用此功能。

关于c# - new() 之后的括号是否存在名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24612730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com