简体   繁体   English

修饰符 'private' 对 C# 中的此项无效

[英]The modifier 'private' is not valid for this item in C#

It gives me such an error and I can't seem to work out what the problem is.它给了我这样的错误,我似乎无法弄清楚问题是什么。

private void Form1.KeyDown(object sender, KeyEventArgs e)  // **THE ERROR HERE**   
    {
        if (ListBox1.Items.Contains(e.KeyCode))
        {
            ListBox1.Items.Remove(e.KeyCode);
            ListBox1.Refresh();
            if (timer1.Interval > 400)
            {

                timer1.Interval -= 10;
            }
            if (timer1.Interval > 250)
            {
                timer1.Interval -= 7;

            }
            if (timer1.Interval > 100)
            {
                timer1.Interval -= 2;

            }
            difficultyProgressBar.Value = 800 - timer1.Interval;
            stats.Update(true);


        }
        else
        {

            stats.Update(false);

        }


        correctLabel.Text = "Correct: " + stats.correct;
        missedLabel.Text = "Missed: " + stats.missed;
        totalLabel.Text = "Total: " + stats.total;
        accuracyLabel.Text = "Accuracy: " + stats.accuracy + "%";


    }

It's code from some tutorial, so it should be working.这是一些教程的代码,所以它应该可以工作。 What could possibly be the problem?可能是什么问题?

You first line should look like this:你的第一行应该是这样的:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    ...
}

Without the dot.没有点。

The dot makes the compiler think you referring to the KeyDown event of the form, while you just want a method which listens to that event.点使编译器认为您指的是表单的 KeyDown 事件,而您只需要一个侦听该事件的方法。

Interfacename.methodname syntax is reserved for explicit interface implementations. Interfacename.methodname 语法保留用于显式接口实现。 Interfaces only contain public methods and thus "private" is illegal.接口只包含公共方法,因此“私有”是非法的。

In VB, when you declare an event handler, you tack on Handles <Class>.<Event> and it automagically hooks everything up for you.在 VB 中,当您声明一个事件处理程序时,您会添加Handles <Class>.<Event>并且它会自动为您连接所有内容。 In C#, you event handlers are just methods that get attached to events.在 C# 中,事件处理程序只是附加到事件的方法。 So you should rename the method name to Form1_KeyDown instead.因此,您应该将方法名称重命名为Form1_KeyDown However, you still need to hook it up (either through the Visual Studio Designer or in the code).但是,您仍然需要连接它(通过 Visual Studio 设计器或在代码中)。

public class Form1 : Form
{
    ...
    public Form1()
    {
        InitializeComponent();
        this.KeyDown += new KeyEventHandler(this.Form1_KeyDown);
    }
    ...
    private void Form1_KeyDown(object sender, KeyEventArgs e) { ... }
}

I just got this error and found I was missing a closing bracket in code above the flagged method.我刚刚收到这个错误,发现我在标记方法上方的代码中缺少一个右括号。 The bad bracket pairs messed up the recognition of private bool method...坏括号对搞乱了私有bool方法的识别......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM