问题
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