是'方法'这在给定的上下文错误中无效
本文关键字:上下文 错误 无效 方法 | 更新日期: 2023-09-27 18:13:25
这个例子来自"Head First CSharp - page 113"我得到以下错误
错误1 'Guys.Form1。joesCashLabel(object, System.EventArgs)'是一个'方法',在给定的上下文中无效c:'temp'Guys'Guys' form .cs 20 12 Guys
其他两个标签也一样
这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Guys
{
public partial class Form1 : Form
{
Guy Joe;
Guy Bob;
int Bank = 100;
public void UpdateForm()
{
joesCashLabel.Text = Joe.Name + "$" + Joe.Money;
bobsCashLabel.Text = Bob.Name + "$" + Bob.Money;
bankCashLabel.Text = "Bank has" + Bank;
}
public Form1()
{
InitializeComponent();
Guy Bob = new Guy();
Bob.Name = "Bob";
Bob.Money =100;
Guy Joe = new Guy();
Joe.Name = "Joe";
Joe.Money =50;
UpdateForm();
}
private void joesCashLabel(object sender, EventArgs e)
{
}
private void bobsCashLabel(object sender, EventArgs e)
{
}
private void bankCashLabel(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (Bank >= 10)
{
Bank -= Joe.ReceiveMoney(10);
UpdateForm();
}
else
{
MessageBox.Show("No money in the bank");
}
}
private void button2_Click(object sender, EventArgs e)
{
Bank = Bank + Bob.GiveMoney(5);
UpdateForm();
}
}
}
这是一个方法(一个事件),
private void joesCashLabel(object sender, EventArgs e)
{
}
但是你把它用作变量
joesCashLabel.Text = Joe.Name + "$" + Joe.Money;
我的猜测是,有某种类型的标签,该事件应该与之关联。
您不能在同一项目中定义具有相同名称的两种类型,这里您有三个具有相同名称的控件和三个事件。因此,删除下面的方法可以使编译没有错误。
private void joesCashLabel(object sender, EventArgs e){}
private void bobsCashLabel(object sender, EventArgs e){}
private void bankCashLabel(object sender, EventArgs e){}
如果要添加事件,请确保遵循ControlName_EventName