加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – new()后括号是否存在名称?

发布时间:2020-12-16 00:11:21 所属栏目:百科 来源:网络整理
导读:我想查询更多关于我偶尔在一些C#代码中看到的构造;但是,我不知道这个名字.如果这是重复,我道歉;然而,在不知道名字的情况下搜索东西非常困难. 构造如下: Person me = new Person(){ Name = "Aelphaeis" } ; 是否有一个特殊的名称来分配像这样的字段/属性?
我想查询更多关于我偶尔在一些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的几天内编写应用程序,那么您就没有这个功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读