简体   繁体   English

在 C# 中创建自定义列表类

[英]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.您不能像在其他一些语言中那样从 C# 的方法中调用基本/备用构造函数。

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.您无需从此处继承 List。 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.类是数据和行为的通用模板,而不是您定义的用于保存 John 的特定信息的东西。

Even better, create a class for the apprioriate thing (a person), and create an instance of a List<Person>更好的是,为适当的事物(一个人)创建一个类,并创建一个List<Person>的实例

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

    ///

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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