2011-09-25 155 views
0

我對C#很陌生,但我每天都在學習越來越多。今天,我試圖構建一個簡單的控制檯計算器,並需要幫助將函數中的變量傳遞給Main(),以便我可以在if-else中使用它來確定執行哪個函數。通過函數傳遞變量到main()

public static void Main(string[] args) 
    { 
     int decision = Introduction(); 
     Console.Clear(); 
     Console.WriteLine(decision); 
     Console.ReadLine(); 
    } 

    public static int Introduction() 
    { 
     int decision = 0; 

     while (decision < 1 || decision > 7) 
     { 
      Console.Clear(); 
      Console.WriteLine("Advanced Math Calculations 1.0"); 
      Console.WriteLine("=========================="); 
      Console.WriteLine("What function would you like to perform?"); 
      Console.WriteLine("Press 1 for Addition ++++"); 
      Console.WriteLine("Press 2 for Subtraction -----"); 
      Console.WriteLine("Press 3 for Multiplication ****"); 
      Console.WriteLine("Press 4 for Division ////"); 
      Console.WriteLine("Press 5 for calculating the Perimeter of a rectangle (x/y)"); 
      Console.WriteLine("Press 6 for calculating the Volume of an object (x/y/z)"); 
      Console.WriteLine("Press 7 for calculating the standard deviation of a set of 10 numbers"); 
      decision = int.Parse(Console.ReadLine()); 

        if (decision < 1 || decision > 7) 
         { 
          decision = 0; 
          Console.WriteLine("Please select a function from the list. Press Enter to reselect."); 
          Console.ReadLine(); 
         } 
        else 
         { 
          break; 
         } 

     } 
     return decision; 
    } 

當我嘗試使用主要決定了(),它說:「這個名字決定不會在當前的背景下存在」。

我很難過,並嘗試使用谷歌搜索無濟於事。

乾杯

SUCCESS!

+0

爲什麼你需要在'Main'和'Introduction'之間共享'決定'? – ebb

回答

1

Introduction返回值。該值是該方法的本地值,並在需要將其返回並分配給局部變量的其他地方使用。或者,你可以讓decision成爲一個靜態類變量,但這不是一個特別好的做法,至少在這種情況下。 Introduction方法(不是一個特別好的名稱,國際海事組織,它應該可能是GetCalculationType(),因爲它是這樣做的)通常不應該有任何副作用。

public static void Main(string[] args) 
{ 

    int decision = Introduction(); 

    ... 

} 

public static int Introduction() 
{ 
    int decision = 0; 

    ... 

    return decision; 
} 
+0

你能解釋一下怎麼會發生? – cSharpNewbie

+0

如果上面的答案沒有告訴你足夠的繼續,你真的需要找到一個關於函數的教程或書籍章節。 –

+0

@cSharpNewbie - 我已經添加了一個例子。 – tvanfosson

1

Main()是您的應用的入口點。然後它會調用您的方法Introduction(),它在堆棧上添加一個新的堆棧幀。因爲你在你的介紹方法中聲明瞭決定變量,所以Main方法不知道它。

如果改爲聲明兩種方法之外的決策變量,你應該能夠從引用它可以:

int decision; 

static void Main(string[] args) 
{ 
    // code here 
} 

static void Introduction() 
{ 
    // code here 
} 
0

,因爲它是本地的功能Introduction您不能使用在主要的decision變量。
你可以讓decision成爲一個靜態類變量,但更好的辦法是從Introduction返回值並將其賦值給main中的局部變量。