collections - How do you create an array-like C# constructor that will allow "new MyClass() { obj1, obj2, obj3 };" -


I am trying to create a class that accepts a dictionary, list or array creator where you Make objects with a literal collection of objects, although I have not found a way to make such a constructor, if this is also possible.

  MyClass obj = new MyClass () {{value1, Value2}, {value3, value4}} 
"post-text" itemprop = "text">

You start the archive Two things need to be done:

  1. Apply IEnumerable (non-normal version)
  2. Add () method matches match initializer

    Here is an example that looks like an idkee:

      class event {static zero main ( String [] arg) {MyClass obj = new MyClass () {{Value1, value2}, {value3, value4}}; }} Public class MyClass: IEnumerable {add public zeros (object x, object y) {} public IEnumerator GetEnumerator () {}}   

    Note that the archive initializer code literally translates this Is:

      MyClass temp = new MyClass (); Temp.Add (value1, value2); Temp.Add (value 3, value 4); Mylace Obze = Temporary;   

    If any addition () calls generates an exception, the named variable (in obj ) is not actually assigned is. The interesting thing is that it also means that if MyClass was implemented to implement IDisposable , then dispose () in it No one will be called on the created item Add () Methods generate an error (I was tested to make sure it).

    Why should IEnumerable ? Because this interface separates classes with classes with add and classes with add to calculate.

    [When you analyze sections with add ], then you know that basically the name has two basic meanings? ?? ADA: ???:

    A) Insert the logic in a collection, or

    b) Return the arithmetic amount and the receiver of the argument

    Also keep in mind that if your collection class IDisposable applies, then you should not use the collection starters if there is any chance that add () throws an exception Or if any one can throw an exception to the expression fed by the add () .



Comments