是一个'方法',在给定的上下文错误中无效

时间:2013-05-14 16:17:39

标签: c#

这是“Head First CSharp - 第113页”的示例 我收到以下错误

  

错误1'Guys.Form1.joesCashLabel(object,System.EventArgs)'是一个'方法',在给定的上下文中无效c:\ temp \ Guys \ Guys \ Form1.cs 20 12个人

与其他两个标签相同

这是代码:

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();
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您不能在具有相同名称的同一项目中定义两种类型,此处您有三个控件和三个具有相同名称的事件。所以删除下面的方法进行编译没有错误。

private void joesCashLabel(object sender, EventArgs e){}

private void bobsCashLabel(object sender, EventArgs e){}

private void bankCashLabel(object sender, EventArgs e){}

如果您想添加活动,请确保遵循ControlName_EventName

等命名标准

答案 1 :(得分:1)

这是一种方法(事件就是这样),

private void joesCashLabel(object sender, EventArgs e)
{

}

但您将其用作变量

joesCashLabel.Text = Joe.Name + "$" + Joe.Money;

我的猜测是,该事件应与之相关联的某种标签。