【发布时间】:2020-10-28 08:27:25
【问题描述】:
public partial class Form1 : Form
{
public void CreateList()
{
List<IRentable> allItems = new List<IRentable>()
{
new VideoBook(06841) {Titel = "Community", Rented = true, GenreType = Genre.Comedy, Actor = AllPeople.ElementAt(0)},
new AudioBook(11585) {Titel = "Deutsch für Dummies", Rented = false, GenreType = Genre.Educational, Author = AllPeople.ElementAt(1)},
new VideoBook(50862) {Titel = "Interstellar", Rented = false, GenreType = Genre.ScienceFiction, Actor = AllPeople.ElementAt(2)},
new AudioBook(98065) {Titel = "The Slim Shady LP", Rented = false, GenreType = Genre.Music, Author = AllPeople.ElementAt(3) },
};
public Form1()
{
InitializeComponent();
CreateList();
}
在这里我需要创建一个新方法(我从表单中获取的一个搜索按钮),我可以在其中访问“allitems”元素
private void searchButton_Click(object sender, EventArgs e)
{
new List<IRentable> SearchResultItems();
var a = titleTextBox.Text;
// here I can't access to allitems
foreach (var elem in allitems)
...
}
}
【问题讨论】:
-
你不能。那是一个局部变量,你离开的那一刻它就消失了
CreateList。 -
将
allItems定义为属性而不是局部变量?