C# 使用对象初始化器有什么好处吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12842371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any benefit of using an Object Initializer?
提问by wayfare
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# 中的使用情况如何?
How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)
回答by AD.Net
Benefits are in the usage of anonymous objects, linq queries, sometimes needless overloading of constructors just to pass parameters
好处是使用匿名对象,linq 查询,有时为了传递参数而不必要地重载构造函数
回答by Jon Senchyna
One often missed benefit is atomicity. This is useful if you're using double-checked lockingon 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:
一个经常被忽视的好处是原子性。如果您在对象上使用双重检查锁定,这很有用。对象初始值设定项在初始化您告诉它的所有成员后返回新对象。来自 MSDN 文章中的示例:
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 studentis never partially initialized. It will either be nullor fully initialized, which is useful in multi-threaded scenarios.
这可确保student永远不会部分初始化。它将被null初始化或完全初始化,这在多线程场景中很有用。
For more info on this, you can check out thisarticle.
有关这方面的更多信息,您可以查看这篇文章。
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).
另一个好处是它允许您创建匿名对象(例如,在 LINQ 中创建投影或连接多个键)。
回答by Kirby
I think that it promotes readability.
我认为它提高了可读性。
As a side note, in the example given in the link shown, I sometimes prefer to have a private setter for the properties (FirstName and LastName), but this depends on your design.
作为旁注,在显示的链接中给出的示例中,我有时更喜欢为属性(名字和姓氏)使用私有设置器,但这取决于您的设计。
回答by Geir Smestad
There is a potential reason to notuse object initializers: If there is an exception during initialization, the call stack in Visual Studio debugger will return only the initializer expression and not the specific line where the exception occurred.
不使用对象初始值设定项有一个潜在的原因:如果在初始化过程中出现异常,Visual Studio 调试器中的调用堆栈将只返回初始值设定项表达式,而不是发生异常的特定行。
If you use libraries or external services that have poorly named exceptions, or alternatively use libraries with native code where you can't see the code that throws the exception (e.g. Xamarin on Android), object initializers can make it harder to debug your code since you don't know which parameter caused the exception to be thrown.
如果您使用具有错误命名异常的库或外部服务,或者在您看不到引发异常的代码的情况下使用带有本机代码的库(例如 Android 上的 Xamarin),则对象初始值设定项会使调试代码变得更加困难,因为您不知道哪个参数导致抛出异常。
Example: Imagine this is your code, but that you can't read the source of ExternalService since it's external to your application. You will not know that it was the "charlie" parameter that caused the error in ExternalService.
示例:假设这是您的代码,但您无法读取 ExternalService 的源代码,因为它在您的应用程序外部。您不会知道是“charlie”参数导致了 ExternalService 中的错误。
var instance = new ClassToBeInitialized
{
alpha = "alpha",
bravo = ExternalService(0),
charlie = ExternalService(1)
};
private static string ExternalService(int parameter)
{
if (parameter == 1)
{
throw new Exception("The external service crashed");
}
return "correctStringResult";
}
回答by Debendra Dash
There are 3 main benefits of object Initialization
对象初始化有 3 个主要好处
Avoid lot of keystrokes,The efficiency of software programs is sometimes measured by the number of keystrokes it requires to write a specific function.
Easy to readable and maintainable.
Time saving approach.
避免大量击键,软件程序的效率有时是通过编写特定功能所需的击键次数来衡量的。
易于阅读和维护。
节省时间的方法。
Let see here how it can avoid lot of keystrokes:
让我们看看它是如何避免大量击键的:
Before c# 3.0 we were doing initialization like this-
在 c# 3.0 之前,我们是这样进行初始化的——
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public string Department { get; set; }
public int salary { get; set; }
}
class Program
{
static void Main(string[] args)
{
Employee emp=new Employee();
emp.Name = "Kumar";
emp.Department = "IT";
emp.Id = 101;
emp.salary = 80000;
Console.ReadLine();
}
}
Now after c# 3.0 we will initialize in one line as follows.
现在在 c# 3.0 之后,我们将在一行中初始化如下。
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee {Name = "Kisan",Id = 55,Department = "IT",salary = 20000};
}
}

