错误:“当前上下文中不存在名称'(变量)'”

时间:2015-12-04 18:24:13

标签: c#

创建Cost的新实例:

Cost newCost = new Cost();

newCost.TotalCost = 0;
newCost.Event = 1000;
newCost.personalEvent = 1500;
newCost.organisationalEvent = 1700; 

然后是它下方的if语句:

if (EventList.SelectedItem == "Event")
{
    TotalCost = (Event + 100);
}
else if (EventList.SelectedItem == "Personal")
{
    TotalCost = (personalEvent + 150);
}

else if (EventList.SelectedItem == "Organisational")
{
    TotalCost = (organisationalEvent + 170);
}
else
{
    txtTotalCost.Text = ("£" + TotalCost.ToString());
}

我还有一个名为Cost的课程,但我一直收到错误"The name 'TotalCost' does not exist in the current context"

任何帮助都会非常感激。

我的Cost课程如下:

class Cost
{
    public int TotalCost;
    public int Event;
    public int personalEvent;
    public int organisationalEvent;
}

1 个答案:

答案 0 :(得分:0)

如果您尝试访问类中的TotalCost字段,则需要提供实例引用,以便计算机知道从哪个对象读取值。

使用TotalCost替换代码中的newCost.TotalCost

if (EventList.SelectedItem == "Event")
{
    newCost.TotalCost = (Event + 100);
}
else if (EventList.SelectedItem == "Personal")
{
    newCost.TotalCost = (personalEvent + 150);
}
else if (EventList.SelectedItem == "Organisational")
{
    newCost.TotalCost = (organisationalEvent + 170);
}
else
{
    txtTotalCost.Text = ("£" + newCost.TotalCost.ToString());
}

顺便说一句,我不清楚为什么只有在设置txtTotalCost.Text字段值时才设置TotalCost。我希望至少在你时设置你想要更新TotalCost属性的txtTotalCost.Text字段值,并且可能只是总是设置它是有意义的它