簡體   English   中英

按鍵警告-如果打算隱藏,請使用新關鍵字

[英]Keypress warning - use the new keyword if hiding was intended

我在void KeyPress(object sender, KeyPressEventArgs e)處不斷收到以下錯誤消息:

警告“ SpeedyRent.Form2.KeyPress(對象,System.Windows.Forms.KeyPressEventArgs)”隱藏了繼承的成員“ System.Windows.Forms.Control.KeyPress”。 如果要隱藏,請使用new關鍵字。

到目前為止,這是我的代碼:

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

具有以下3個參考:

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

是什么原因造成的?

您的方法名為KeyPress ,但是已經有一個從Control繼承的名為KeyPress的事件。 嘗試使用不會與任何繼承的成員沖突的名稱,如下所示:

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

另請注意,您可以像這樣綁定事件:

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

是什么原因造成的?

您要聲明的方法與基類中聲明的事件同名。 事件隱藏在派生類中,這通常不是一個好主意。

兩種選擇:

  • 按照編譯器的建議使用new
  • 只是重命名方法

就我個人而言,我將采用后一種方法,為該方法命名一個實際上說明其作用的名稱:

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

您還可以使用比以前更少的冗長語法進行預訂,並進行方法組轉換:

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

無論您擁有該方法的任何類( KeyPress )都繼承自已經具有非virtual KeyPress方法的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM