[英]Creating a List<Book> c# console application
我想創建一個List,其中包含幾本書,書名,作者姓名和出版年份。 例如:(AuthorLastName,AuthorFirstName,“書名”,年份。)
我知道如何創建List<int>
,例如:
class Program
{
static void Main()
{
List<int> list = new List<int>();
list.Add(10);
list.Add(20);
list.Add(25);
list.Add(99);
}
}
但問題是,如果我想創建一個書籍列表,我不能簡單地創建一個list<string>
或list<int>
因為我希望它包含字符串和int(如上例所示)。
那么,任何人都可以解釋我如何制作一本書籍清單嗎?
您需要創建一個名為Book
的class
,其中包含您想要的屬性。 然后,您可以實例化List<Book>
。
例:
public class Book
{
public string AuthorFirstName { get; set; }
public string AuthorLastName { get; set; }
public string Title { get; set; }
public int Year { get; set; }
}
然后,使用它:
var myBookList = new List<Book>();
myBookList.Add(new Book {
AuthorFirstName = "Some",
AuthorLastName = "Guy",
Title = "Read My Book",
Year = 2013
});
你需要定義你的類:
public class Book
{
public string Author { get; set; }
public string Title { get; set; }
public int Year { get; set; }
}
然后你可以列出它們:
var listOfBooks = new List<Book>();
做這樣的事情
public class Book
{
public string AuthorLastName { get; set; }
public string AuthorFirstName{ get; set; }
public string Title{ get; set; }
public int Year { get; set; }
}
List<Book> lstBooks = new List<Book>();
lstBooks.Add(new Book()
{
AuthorLastName = "What",
AuthorFirstName = "Ever",
Title = Whatever
Year = 2012;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.