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

I am trying to create a class that accepts a constructor similar to a dictionary, list, or array constructor, where you can create an object with a literal set of objects, although I could not find how to create such a constructor, even if it is possible.

MyClass obj = new MyClass()
{
    { value1, value2 },
    { value3, value4 }
}
+5
source share
3 answers

Two things are needed for a collection initializer:

  • Deploy IEnumerable(not generic version)
  • Add()that corresponds to the collection initializer

Here is an example similar to IDictionary:

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass()
        {
            {value1, value2},
            {value3, value4}
        };
    }
}

public class MyClass : IEnumerable
{
    public void Add(object x, object y)
    {

    }

    public IEnumerator GetEnumerator()
    {
    }
}

Note that the collection initializer code literally translates into this:

MyClass temp = new MyClass();
temp.Add(value1, value2);
temp.Add(value3, value4);
MyClass obj = temp;

- temp, - Add() , (obj ) . , , MyClass IDisposable, Dispose() , Add() ( , ).

IEnumerable? Add Add .

http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx

[ Add] , "":

a)

b)

, IDisposable, , , Add() - , Add(), .

https://connect.microsoft.com/VisualStudio/feedback/details/654186/collection-initializers-called-on-collections-that-implement-idisposable-need-to-call-dispose-in-case-of-failure#

+10

:

public class MyClass
{
    public MyClass() {}
    public MyClass(params object[] list) { ... }
}
+1

Is the default value appropriate?

new MyClass {
   MyCol = {Value1, Value2, ... },
};
-2
source

All Articles