首页 > 解决方案 > 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)
        ...
    }
}

标签: c#listmethods

解决方案


您可能希望在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)
        ...
    }
}

推荐阅读