使用对象初始化器有什么好处吗? [英] Is there any benefit of using an Object Initializer?

查看:24
本文介绍了使用对象初始化器有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C# 对象初始值设定项有什么好处吗?

Are there any benefits in using C# object initializers?

在 C++ 中,没有引用,所有内容都封装在一个对象中,因此在创建对象后使用它们而不是初始化成员是有意义的.

In C++ there are no references and everything is encapsulated inside an object so it makes sense to use them instead of initializing members after object creation.

它们在 C# 中的使用情况如何?

What is the case for their use in C#?

如何:使用对象初始值设定项初始化对象(C# 编程指南))

推荐答案

一个经常被忽视的好处是原子性.如果您在对象上使用双重检查锁定,这将非常有用.对象初始值设定项在初始化您告诉它的所有成员后返回新对象.来自 MSDN 文章中的示例:

One often missed benefit is atomicity. This is useful if you're using double-checked locking on an object. The object initializer returns the new object after it has initialized all of the members you told it to. From the example on the MSDN article:

StudentName student = new StudentName
{
    FirstName = "Craig",
    LastName = "Playstead",
    ID = 116
};

将被翻译成如下内容:

StudentName _tempStudent = new StudentName();
_tempStudent.FirstName = "Craig";
_tempStudent.LastName = "Playstead";
_tempStudent.ID = 116;

StudentName student = _tempStudent;

这确保了 student 永远不会被部分初始化.它将是 null 或完全初始化,这在多线程场景中很有用.

This ensures that student is never partially initialized. It will either be null or fully initialized, which is useful in multi-threaded scenarios.

有关这方面的更多信息,您可以查看 这篇 文章.

For more info on this, you can check out this article.

另一个好处是它允许您创建匿名对象(例如,在 LINQ 中创建投影或连接多个键).

Another benefit is that it allows you to create anonymous objects (for instance, to create a projection or to join on multiple keys in LINQ).

这篇关于使用对象初始化器有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆