c# - 我无法访问我创建的列表
问题描述
我正在创建一个控制台应用程序,它将为 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
期望我可以只使用我认为可以开始使用该列表的列表,但在此自定义方法中无法访问它。
解决方案
你List
被声明为类的成员变量Program
,而方法LoadMagic8responses
是静态的。您需要研究静态变量和成员变量/方法之间的区别。本质上,静态方法在任何实例的上下文之外执行,因此无法访问仅存在于实例上下文中的成员变量。
推荐阅读
- .net-core - Windows Server:找不到指定的框架“Microsoft.AspNetCore.App”,版本“2.1.0”
- python - 创建我自己的登录表单 django
- azure - 使用 ClaimsTransformation 中的 FormatStringClaim 转换方法删除数字之间的“-”连字符
- javascript - Discord.js 仅使用他的 ID 获取用户保存在数据库中的内容
- r - 正则表达式模式 r 的对面
- mysql - 谷歌云 SQL 备份忽略某些表
- r - geom_bar() 绘制线条而不是条形
- c - 空函数 C
- python - Pandas - 组合两个未堆叠的数据框
- selenium - 需要在 Selenium Chrome Webdriver 中循环覆盖代理