简体   繁体   中英

Creating a custom list class in C#

I want to create a class that is a Custom List. So I have done

 public class Set1 : List<Dictionary<string, string>>
    {

    public Set1() : base(List<Dictionary<string, string>>)         
    {
        List<Dictionary<string, string>> mySet = new List<Dictionary<string, string>>()
        {
            new Dictionary<string, string>()
            {
                {"first_name","John"},
            },
            new Dictionary<string, string>()
            {
                {"last_name","Smith"},
            },

        };

        base(mySet);

    }
}

But this does not compile. What am I doing wrong please? Thanks in advance.

You can't call a base/alternate constructor from within the method in C# like you can in some other languages.

However, you don't need to call the base constructor in this case - you can just do:

public Set1()        
{
    this.Add(
        new Dictionary<string, string>()
        {
            {"first_name","John"},
        }
    );
    this.Add(
        new Dictionary<string, string>()
        {
            {"last_name","Smith"},
        }

    );
}

If you really want to call the base constructor, though, you'll have to inline the list creation in the declaration:

public Set1()        
 : base( new List<Dictionary<string, string>>
            {
                new Dictionary<string, string>()
                {
                    {"first_name","John"},
                },
                new Dictionary<string, string>()
                {
                    {"last_name","Smith"},
                }
            }
        )
{
    // nothing more to do here
}

but that creates a list, only to have the constructor copy the items into the list, increasing your memory usage for a short time.

Here is the code you're looking for

new Dictionary<string, string>() {
          {"first_name","John"}, {"last_name","Smith"},
      }.

You don't have any need to inherit from List here. What you wanted was an instance of some collection. A class is a general template for data and behaviour, not something you define to hold the specific information for John.

Even better, create a class for the apprioriate thing (a person), and create an instance of a List<Person>

    public class Person
    {
        public string Forename {get;set;}
        public string Surname {get;set;}
    }

    ///

    var people = new List<Person>() { new Person("John", "Smith") };

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