2017-02-27 58 views
-2

如果可以,請幫助我理解這一點。我只有幾個月的時間學習C#,並且似乎錯過了一些東西。我瞭解如何創建方法,但似乎無法檢索要在其之外使用的數據。請參閱我剛剛創建的這個示例,嘗試創建一個從1到20的數字,然後覆蓋現有變量的方法。使用方法返回的數據

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

namespace _170227 
{ 
    class Program 
    { 


     static void Main(string[] args) 
     { 
      int x = 0; 

      d20(); 
      Console.WriteLine(x); 

     } 


     static int d20() 
     { 
      Random myRandom = new Random(); 
      int x = myRandom.Next(20) + 1; 
      return x; 


     } 

    } 

} 

什麼我需要做的,有一個方法,從一些進一步的使用不是方法本身定義的方法處理現有變量或生成的數據?先謝謝你!

+6

'D20();' - >'X = D20();'' –

+1

Console.WriteLine(D20());' – Equalsk

+1

除了'X = D20()',如果我是你,我會在'd20()'裏面重命名'x' *,並且只在'd20()'*裏面重命名爲'y'或'charltonHeston'或絕對世界上除'x'之外的任何東西,在'd20()'中聲明的'x'與任何其他的'x'完全無關,名稱中的相似性是無意義或無意義的巧合。 –

回答

3

xd20()方法內是不一樣的變量作爲在從中調用d20範圍的x。你需要告訴你想有從存儲在後者中d20輸出編譯器,與分配:

static void Main(string[] args) 
{ 
    int x = 0; 

    x = d20(); 
    Console.WriteLine(x); 
} 

您可以在同一份聲明中宣佈並指派x如果你喜歡:

static void Main(string[] args) 
{ 
    int x = d20(); 
    Console.WriteLine(x); 
} 
1

您需要將您的方法返回的值分配給您的變量。

嘗試

int x = d20(); 
5

方法的返回值就分配給變量x這樣

static void Main(string[] args) 
    { 
     int x = 0; 

     x = d20(); 
     Console.WriteLine(x); 
    } 

    static int d20() 
    { 
     Random myRandom = new Random(); 
     int x = myRandom.Next(20) + 1; 
     return x; 
    } 
0

記住一個事實,即您的兩個方法有一個變種從編譯器的角度來看,他們名爲x純粹是巧合 - 他們絕對不會指同一件事。作爲一個比喻,我知道幾個和我一樣名字的人,但他們是而不是我。

正如其他人所指出的,您需要將返回值d20()存儲在一個變量(即int x = d20();)中。

2

解釋爲什麼發生這種情況需要了解範圍

在你的例子中,你聲明x與所謂的本地範圍。也就是說,x只存在於您聲明它的方法中。

在此示例中,x只存在於名爲Main的方法中。

static void Main(string[] args) 
{ 
    int x = 0; 
} 

如果你的命名d20方法看上去像這樣,你就會得到一個編譯時錯誤說x沒有定義。

static int d20() 
{ 
    Random myRandom = new Random(); 
    x = myRandom.Next(20) + 1; // Error would occur here 
    return x; 
} 

這是因爲d20有它自己的範圍是從Main分開。

有幾個不同的答案:

最短的僅僅是Console.WriteLine(d20());。這告訴程序打印從方法d20返回的結果。

或者你可以調整你的代碼,這樣,其分配的d20x結果。

static void Main(string[] args) 
{ 
    int x = d20(); 
    Console.WriteLine(x); 
} 

static int d20() 
{ 
    Random myRandom = new Random(); 
    return myRandom.Next(20) + 1; 
} 

最後你可以通過聲明xMain使用較高的範圍。

int x; 

static void Main(string[] args) 
{ 
     d20(); 
     Console.WriteLine(x); 
} 

static void d20() 
{ 
    Random myRandom = new Random(); 
    x = myRandom.Next(20) + 1; 
}