C# 字段';xxx和x27;从未分配给,并且其默认值始终为空
我的错误:C# 字段';xxx和x27;从未分配给,并且其默认值始终为空,c#,C#,我的错误: 字段“StockManagement.LargeItems1.largeS”从未分配给,并且其默认值始终为null 我的代码: namespace StockManagement { class LargeItems1 { private Stack<string> largeS; public LargeItems1() { Stack<string> largeS
字段“StockManagement.LargeItems1.largeS”从未分配给,并且其默认值始终为null
我的代码:
namespace StockManagement
{
class LargeItems1
{
private Stack<string> largeS;
public LargeItems1()
{
Stack<string> largeS = new Stack<string>();
}
public void LargeItemsAdd()
{
string usersInput2, tempValue;
int tempValueI = 0;
bool attempt = false;//, whichOne = false;
Console.WriteLine("Would you like to remove or add an item to the storage area \n Reply add OR remove");
string usersInput = Console.ReadLine();
usersInput = usersInput.ToLower();
if (usersInput.Contains("remove"))
{
LargeItemsRemove(largeS);
return;
}
else if (usersInput.Contains("add"))
{
Console.WriteLine("Please input (numerically) how many IDs you'd like to add");
tempValue = Console.ReadLine();
attempt = int.TryParse(tempValue, out tempValueI);
while (!attempt)
{
Console.WriteLine("Please input (numerically) how many IDs you'd like to add, you did not input a numeric value last time");
tempValue = Console.ReadLine();
attempt = int.TryParse(tempValue, out tempValueI);
}
for (int i = 0; i < tempValueI; i++)
{
Console.WriteLine("Please input the ID's (one at a time) of the item you would like to add");
usersInput2 = Console.ReadLine();
if (largeS.Contains(usersInput2))
{
Console.WriteLine("That ID has already been stored");
}
else
{
largeS.Push(usersInput2);
}
}
foreach (var item in largeS)
{
Console.WriteLine("Current (large) item ID's: " + item);
}
}
}
public void LargeItemsRemove(Stack<string> largeS)
{
if (largeS.Contains(null))
{
Console.WriteLine("No IDs stored");
}
else
{
string popped = largeS.Pop();
foreach (var item in largeS)
{
Console.WriteLine("Pop: " + item);
}
Console.WriteLine("Removed ID = " + popped);
}
}
}
}
名称空间库存管理
{
类大项目1
{
私有堆栈大容量;
公共大型项目1()
{
Stack largeS=新堆栈();
}
公共无效的大项目
{
字符串usersInput2,tempValue;
int tempValueI=0;
bool-trument=false;/,whichOne=false;
Console.WriteLine(“是否要将项目删除或添加到存储区域\n答复添加或删除”);
字符串usersInput=Console.ReadLine();
usersInput=usersInput.ToLower();
if(usersInput.Contains(“remove”))
{
大项目搬迁(大项目);
返回;
}
else if(usersInput.Contains(“add”))
{
WriteLine(“请输入(数字)您要添加多少ID”);
tempValue=Console.ReadLine();
尝试=int.TryParse(tempValue,out tempValueI);
而(!尝试)
{
WriteLine(“请输入(数字)您要添加的ID数量,您上次没有输入数字值”);
tempValue=Console.ReadLine();
尝试=int.TryParse(tempValue,out tempValueI);
}
对于(int i=0;i
我不知道如何将我的值分配给实例。我将感谢任何能提供的帮助 更改构造函数以初始化字段而不是局部变量:
public LargeItems1()
{
this.largeS = new Stack<string>();
}
public LargeItems1()
{
this.largeS=新堆栈();
}
您必须使用this
关键字以以下方式初始化字段largeS
:
this.largeS = new Stack<string>();
您只是初始化一个新的局部变量,它与您的私有字段无关
查看MSDN文档中的关键字。您需要将其定义为字段或属性,而不是构造函数中的局部变量。编辑:关于类的更多信息:EDITx2:Oops,忽略了它被声明为一个字段的事实,我现在看到它的格式是固定的;谢谢你,蒂姆。很好的解释!!谢谢,我只是在MSDN上查找这个关键字,你的解释帮助我理解了:)。
Stack<string> largeS = new Stack<string>();