Difference between class initializers in C#? [duplicate]

柔情痞子 提交于 2021-01-27 04:11:13

问题


Possible Duplicate:
Why are C# 3.0 object initializer constructor parentheses optional?

What is the difference between instatiating an object by using

classInstance = new Class() { prop1 = "", prop2 = "" };

and

classInstance = new Class { prop1 = "", prop2 = "" };


回答1:


Nothing. The second is just a short-cut for the first. The first allows you to include arguments to a constructor. So, you can't use the short-cut if the class doesn't have an empty constructor.

You may have an interest in this question:

Why are C# 3.0 object initializer constructor parentheses optional?

And Eric Lippert´s great blog post:

Ambiguous Optional Parentheses, Part One




回答2:


Short answer: Nothing. The () can be used if you want to pass in some constructor args but in your case since you don't have any, you can skip ().

For eg. () is useful here.

  Foo foo = new Foo(someBar){Prop1 = "value1", Prop2 = value2};

but if you are trying to call the parameter-less constructor, it's optional

  Foo foo = new Foo {Prop1 = "value1", Prop2 = value2};



回答3:


There is no difference other than syntax, you are still calling the parameter-less constructor either way.



来源:https://stackoverflow.com/questions/6310200/difference-between-class-initializers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!