C#中类初始值设定项的区别?

时间:2011-06-10 17:50:01

标签: c# .net class object instantiation

  

可能重复:
  Why are C# 3.0 object initializer constructor parentheses optional?

使用

实例化对象有什么区别

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

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

3 个答案:

答案 0 :(得分:6)

简短回答:没什么。如果你想传递一些构造函数args,可以使用() 在你的情况下,因为你没有,你可以跳过()

例如。 ()在这里很有用。

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

但是如果你试图调用无参数构造函数,那么它是可选的

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

答案 1 :(得分:4)

无。第二个是第一个的捷径。第一个允许您包含构造函数的参数。因此,如果类没有空构造函数,则不能使用快捷方式。

您可能对此问题感兴趣:

Why are C# 3.0 object initializer constructor parentheses optional?

Eric Lippert的博客文章:

Ambiguous Optional Parentheses, Part One

答案 2 :(得分:3)

除了语法之外没有其他区别,你仍然以任何方式调用无参数构造函数。

相关问题