简体   繁体   中英

How to implement default method like StringCollection and some class does?

While answering a question i came upon this

StringCollection sc = new StringCollection();

sc.Add("Foo");

But this can be written as

StringCollection sc = new StringCollection() {"Foo"};

and this cannot be written

StringCollection sc = new StringCollection() {new string[] {"Foo"} };

That means Add method is called and AddRange is not.

How can i make a class that can have this functionality of having a default method called while creating its object?

It's called a Collection Initializer . The class must implement IEnumerable and have a public Add method.

The class can have multiple Add methods, eg

public class MyCollection : IEnumerable
{
    public void Add(string item) { ... }

    public void Add(string[] items) { ... }

    ...
}

The code is a collection initializer : http://msdn.microsoft.com/en-us/library/bb384062.aspx

Collection initializers let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.

The call to "Add" is generated by the compiler. So unless you write your own C# compiler, you cannot customize the behavior to call "AddRange".

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