c# - C# - 如何从另一个方法访问方法内的列表?
问题描述
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)
...
}
}
解决方案
您可能希望在类newItems
范围内定义列表,而不是在函数范围内,这样您就可以在类中的任何位置访问它。
如果您在 Form1 的类范围内定义 newItems,您的代码如下所示:
public partial class Form1 : Form
{
// Notice that this variable is defined outside of functions, but its
// value has ben set inside CreateList(), so before CreateList() is
// called, this variable contains null.
List<IRentable> allItems;
public void CreateList()
{
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();
}
private void searchButton_Click(object sender, EventArgs e)
{
// You can access allItems variable here, because both CreateList()
// and searchButton_Click() functions are within the class scope,
// where the variable was defined.
foreach (var elem in allItems)
...
}
}
推荐阅读
- excel - 将数据从另一个打开的工作簿复制到主工作簿而不指定 FileName
- python - pip 未在 setup.py 中安装所有依赖项
- wget - wget更改域名
- r - 我应该怎么做才能看到特定对象的代码,而不是 R 中该对象的结果?
- php - 为什么 Wordpress 的 'save_post_{$post->post_type}' 动作钩子没有传递正确数量的参数?
- php - 登录错误密码和用户名组合
- scala - 当演员失败时,Akka 是否会自动复制变量
- mysql - 如何在mysql中使用查询获取多条记录
- javascript - 使用 xml-builder 节点模块打印尖括号的问题
- java - 2 使用 itext5 的带有图像的并行表