[英]Creating a custom list class in C#
我想創建一個自定義列表類。 所以我做了
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);
}
}
但這不能編譯。 請問我做錯了什么? 提前致謝。
您不能像在其他一些語言中那樣從 C# 的方法中調用基本/備用構造函數。
但是,在這種情況下您不需要調用基本構造函數 - 您可以這樣做:
public Set1()
{
this.Add(
new Dictionary<string, string>()
{
{"first_name","John"},
}
);
this.Add(
new Dictionary<string, string>()
{
{"last_name","Smith"},
}
);
}
但是,如果您真的想調用基本構造函數,則必須在聲明中內聯列表創建:
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
}
但這會創建一個列表,只會讓構造函數將項目復制到列表中,從而在短時間內增加內存使用量。
這是您正在尋找的代碼
new Dictionary<string, string>() {
{"first_name","John"}, {"last_name","Smith"},
}.
您無需從此處繼承 List。 您想要的是某個集合的實例。 類是數據和行為的通用模板,而不是您定義的用於保存 John 的特定信息的東西。
更好的是,為適當的事物(一個人)創建一個類,並創建一個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.