是否有使用对象初始化的任何利益? [英] Is there any benefit of using an Object Initializer?

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

问题描述

有没有在使用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
};

将被转换为类似如下:

Would be translated to something like the following:

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

StudentName student = _tempStudent;

这确保了学生从不部分初始化。这要么是或完全初始化,这是在多线程的情况下非常有用。

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

有关这方面的详细信息,你可以检查出<一href="http://community.bartdesmet.net/blogs/bart/archive/2007/11/22/c-3-0-object-initializers-revisited.aspx">this文章

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天全站免登陆