How to design an immutable object with complex initialization

后端 未结 6 1168
北恋
北恋 2021-02-02 15:59

I\'m learning about DDD, and have come across the statement that \"value-objects\" should be immutable. I understand that this means that the objects state should not change aft

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 16:58

    At the moment, you'd have to use a constructor with lots of args, or a builder. In C# 4.0 (VS2010), you can use named/optional arguments to achieve something similar to C# 3.0 object-initializers - see here. The example on the blog is:

      Person p = new Person ( forename: "Fred", surname: "Flintstone" );
    

    But you can easily see how something similar can apply for any constructor (or other complex method). Compare to the C# 3.0 object-initializer syntax (with a mutable type):

     Person p = new Person { Forename = "Fred", Surname = "Flintstone" };
    

    Not much to tell them apart, really.

    Jon Skeet has posted some thoughts on this subject too, here.

提交回复
热议问题