简体   繁体   中英

Keypress warning - use the new keyword if hiding was intended

I keep getting the following error message at void KeyPress(object sender, KeyPressEventArgs e) :

Warning 'SpeedyRent.Form2.KeyPress(object, System.Windows.Forms.KeyPressEventArgs)' hides inherited member 'System.Windows.Forms.Control.KeyPress'. Use the new keyword if hiding was intended.

This is my code so far:

void KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

with the following 3 references:

this.totalTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);
this.remainTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);
this.paidTxt.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress);

What is causing it?

Your method is named KeyPress , but the there is already an event named KeyPress inherited from Control . Try using a name that won't conflict with any inherited members, like this:

private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

Also note, you can bind your events like this:

this.totalTxt.KeyPress += this.TextBox_KeyPress;
this.remainTxt.KeyPress += this.TextBox_KeyPress;
this.paidTxt.KeyPress += this.TextBox_KeyPress;

What is causing it?

You're declaring a method with the same name as an event declared in a base class. That hides the event within the derived class, which isn't a good idea in general.

Two options:

  • Use new as the compiler suggests
  • Just rename the method

Personally I'd take the latter approach, giving the method a name which actually says what it does:

private void SuppressNonDigits(object sender, KeyPressEventArgs e)
{
    ...
}

You can also subscribe using rather less verbose syntax than before, with method group conversions:

totalTxt.KeyPress += SuppressNonDigits;
remainTxt.KeyPress += SuppressNonDigits;
paidTxt.KeyPress += SuppressNonDigits;

无论您拥有该方法的任何类( KeyPress )都继承自已经具有非virtual KeyPress方法的类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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