2016-07-05 28 views
-3

我正在使用Windows窗體應用程序,其中有一個TextBox,並且我有一個事件textBox1_KeyDown,它觸發一個函數,該函數位於另一個類中,該函數在調用它之後調用對象和所有設置都是默認設置。但是我提示以下錯誤:爲...由於其在C#中的保護級別而無法訪問函數

錯誤CS0122「ClassName.FunctionName(對象,KeyEventArgs)」是 無法訪問由於其保護級別

現在我的主窗體的代碼是什麼像下面...

namespace NewDEMOApps 
{ 
    public partial class MainForm : Form 
    { 
     ClassName newObj = new ClassName(); 

     public MainForm() 
     { 
      InitializeComponent(); 
     } 

     private void textBox1_KeyDown(object sender, KeyEventArgs e) 
     { 
      newObj.FunctionName(sender, e); 
     }  
    } 
} 

我的類代碼是一樣的東西下面...

namespace NewDEMOAppsClass 
{ 
    public class ClassName 
    { 
     private void FunctionName(object sender, KeyEventArgs e) 
     { 
      if (true) 
      { 
       if (e.KeyCode.Equals(Keys.Up)) 
       { 
        MessageBox.Show(UP Key Pressed); 
       } 
       if (e.KeyCode.Equals(Keys.Down)) 
       { 
        MessageBox.Show(DOWN Key Pressed); 
       } 
       if (e.KeyCode.Equals(Keys.Enter)) 
       { 
        MessageBox.Show(Enter Key Pressed); 
       } 
       e.Handled = true; 
      } 
     } 
    } 
} 

現在我想通過務實的方式解決這個問題,而不是通過編輯/更改Visual Studio中的GUI設置等。所以,我可以做任何事情來解決這個問題嗎?

+1

將'private void FunctionName(object sender,KeyEventArgs e)'改爲'public void FunctionName(object sender,KeyEventArgs e)'。您通常不能從其課程外部訪問私有方法。 [https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx](https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx) – Draken

+1

[公共','默認','受保護'和'私人'之間的差異可能存在重複'](http://stackoverflow.com/questions/215497/difference-among-public-default-protected-and-private) –

+0

@Draken有一個愚蠢的錯誤,請在回答中添加您的評論,以便我將選擇它。 :P –

回答

1

更改如下:

private void FunctionName(object sender, KeyEventArgs e) 

public void FunctionName(object sender, KeyEventArgs e) 

你一般不能從它的類之外訪問private方法。 Read here for further information

相關問題