简体   繁体   中英

C# array-like constructor for own class

I want to create a custom class that can be initialized like arrays can,

var myCollection = new MyCollection<string> {"a", "b", "c"}

Is there a syntax for creating a class that can interpret that?

I know how to do a similar thing with class properties, such as

var person = new Person { Name = "Santi", LastName = "Arizti" };

But that is not what I am looking for.

This question might already exist, but I just don't know the name of this feature to effectively search it online.

Your class must

  1. Implement IEnumerable
  2. Have an Add method

That's it.

public class MyCollection<T> : IEnumerable<T>
{
    protected readonly List<T> _list = new List<T>();

    public void Add(T item) 
    {
        _list.Add(item);
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }
}

public class Program
{
    public static void Main()
    {
        var x = new MyCollection<string>
        {
            "A","B"
        };
    }
}

Here is a Link to Fiddle

Constructing an object using {...} simply creates it using the default constructor and calls an Add method present on it for each of the arguments (or tuples of arguments if nested {...} is used). It only has to implement IEnumerable .

Your example is essentially equivalent to:

var myCollection = new MyCollection<string>();
myCollection.Add("a");
myCollection.Add("b");
myCollection.Add("c");

Here's the simplest example of such a class that can be "initialized" with anything:

public class TestClass : IEnumerable
{
    public void Add<T>(params T[] args)
    {

    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM