2015-12-28 40 views
-2

我有一個Class和一個Form。這是我在我的表單代碼:C#名稱在當前上下文中不存在

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Tamagotchi 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      label3.Text = "doplntamboredom"; 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 

     } 

     private void button3_Click(object sender, EventArgs e) 
     { 
      label6.Text = GetMood(); 
     } 
    } 
} 

這最後一部分(label6.Text = GetMood())正在錯誤:

The name 'GetMood' does not exist in the current context.

這是我在我的類代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Tamagotchi 
{ 
    class Mazlicek 
    { 
     private int hunger = 1; 
     private int boredom = 1; 

     private string mood; 
     public string GetMood() 
     { 
      return mood; 
     } 

     private void Moods(int hunger, int boredom, string strHunger, string strBoredom) 
     { 
      if ((boredom + hunger) > 15) 
      { 
       mood = "Angry!"; 
      } 
      else if ((boredom + hunger) > 10 && (boredom + hunger) < 15) 
      { 
       mood = "Frustrated.."; 
      } 
      else if ((boredom + hunger) > 5 && (boredom + hunger) < 11) 
      { 
       mood = "Fine."; 
      } 
      else 
      { 
       mood = "Happy!"; 
      } 
     } 

    } 
} 

我不知道爲什麼有這個問題。我正在使用Visual Studio 2015,它都在一個項目中。

+0

您的表單中的「Mazlicek」實例在哪裏?你爲什麼試圖從沒有定義的地方調用'GetMood'? –

+2

你的'情緒'方法是'私人',所以沒有人可以稱之爲。即使你創建了一個實例來修復代碼,GetMood()總是返回null。 –

+0

https://msdn.microsoft.com/library/x9afc042(v=vs.110).aspx請閱讀本文以及https://msdn.microsoft.com/en-us/library/79b3xss3.aspx – MethodMan

回答

0

使用

label6.Text = Mazlicek.GetMood(); 

,並更改爲

static class Mazlicek 

private static string mood; 

public static string GetMood() 
{ 
    return mood; 
} 
+3

否;他可能應該有一個實例。 – SLaks

+0

但是沒有構造函數......也許它是靜態的? – J3soon

+3

不一定有明確定義的構造函數。 –

3

您可能的意思是在您的表單中有一個Mazlicek的實例。這樣你可以調用它的方法。

所以,通過實例變量mazlicekMazlicek類型的實例入手:

public partial class Form1 : Form 
{ 
    private Mazlicek mazlicek = new Mazlicek(); 

    ... 
} 

現在我們有一個實例化對象,你可以可以調用它的方法和設置屬性記住它的狀態。您必須通過變量名稱mazlicek來引用它:

private void button3_Click(object sender, EventArgs e) 
{ 
    label6.Text = mazlicek.GetMood(); 
} 
相關問題