首页 > 解决方案 > 我无法访问我创建的列表

问题描述

我正在创建一个控制台应用程序,它将为 Y/N 问题生成随机答案。我需要使用一个列表(而不是字典)在一个简单的文本文件中阅读我的回复。问题是我创建的列表(我在课堂上创建的)无法使用,就像我没有创建它一样。

我尝试仔细检查我的语法,关闭 Visual Studio 并再次打开它并确保我将它放在同一个类中

//the below code is where I created the list
 class Program
    {
        // we need to create a list we can use
        List<string> Magicresponses = new List<string>();
//the below code is where I tried to use the list
private static void LoadMagic8responses()
        {
            // create a variable for our file
            StreamReader inputfile;
            try
            {
                inputfile = File.OpenText("8ball_file.txt");
                while (!inputfile.EndOfStream)
                {
                    //this is where I am trying to use the list 

期望我可以只使用我认为可以开始使用该列表的列表,但在此自定义方法中无法访问它。

标签: c#

解决方案


List被声明为类的成员变量Program,而方法LoadMagic8responses是静态的。您需要研究静态变量和成员变量/方法之间的区别。本质上,静态方法在任何实例的上下文之外执行,因此无法访问仅存在于实例上下文中的成员变量。


推荐阅读