Possible to mix object initializer and collection initializer?

后端 未结 5 1700
猫巷女王i
猫巷女王i 2020-12-18 21:46

I define an collection initializer with IEnumerable as instructed here: http://msdn.microsoft.com/en-us/library/bb384062.aspx

Now I\'m able to create objects within

5条回答
  •  天涯浪人
    2020-12-18 22:39

    Storage-location initializers are in theory supposed to create new objects with a given state, as opposed to causing objects to progress through a series of states. Code which is supposed to put something through a series of states is supposed to be written in an object's constructor.

    Initializing a storage location (field, variable, etc.) with a constant simply sets its value once. Initializing a variable with a constructor or method call will cause the method to be given everything it will need before it starts, but will do nothing to the variable until the method returns. Thus it too avoids any apparent succession of states.

    Property initializers and collection initializers both violate this pattern, but operate on the assumption that many classes are designed so that creating an object and setting some properties before exposing the reference to outside code will yield results indistinguishable from an object instantaneously coming into existence with those properties. Likewise, collection initializers assume that creating a collection and then calling Add with a sequence of items will yield results indistinguishable from the collection coming into existence holding the correct values.

    Not all classes which expose properties will yield the expected behavior when used with property initializers, and not all classes look like collections will yield the expected behavior when used with collection initializers, but the compiler is willing to "guess" that classes which are used with property initializers will conform to the normal property pattern, and likewise for classes which are used with collection initializers.

    If setting up an object would require both calling property setters and an item-Add method, however, that would imply that the object is not a typical things with property setters, nor is it a typical collection. There would be no particular reason for the language to dictate that property setters would be invoked before items are added, nor would there any particular reason to specify that they would be invoked after. One could allow the C# source code for the initializers to specify the order in which they run, but such specification would explicitly acknowledge that the sequence of operations would affect the object's state in ways not expressed within the initializer itself. Such side-effects would tend to imply that the code in question belongs within a constructor rather than a field initializer.

提交回复
热议问题