What's the difference between an object initializer and a constructor?

后端 未结 7 1388
温柔的废话
温柔的废话 2020-11-22 12:23

What are the differences between the two and when would you use an \"object initializer\" over a \"constructor\" and vice-versa? I\'m working with C#, if that matters. Als

7条回答
  •  旧巷少年郎
    2020-11-22 12:34

    If you have properties that MUST be set on your object for it to work properly, one way is to expose just a single constructor which requires those mandatory properties as parameters.

    In that case, you cannot create your object without specifying those mandatory properties. Something like that cannot be enforced by object initializers.

    Object initializers are really just a "syntax convenience" to shorten initial assignments. Nice, but not really very functionally relevant.

    Marc

提交回复
热议问题