2014-03-26 51 views
0

從今天開始,我是c#中的總noob。我找不到一個好的教程或任何東西,可以解決這個顯然愚蠢的問題。基本上,我嘗試將一個程序從Python轉換爲C#。通常在Python中我在構造函數中定義常量。我應該把它們放在C#中嗎?我試圖把它們放在構造函數中,然後把它們放在Main()中,因爲出現了這個錯誤。但錯誤仍然存​​在。該名稱在當前上下文中不存在?

static void Main(string[] args) 
    { 
    var _top = 0 
    ... 
    } 
public string[] topToken() 
    { 
     if (_top < _tokens.Count()) 
     { return _tokens[_top];} 
+1

你使用的是哪個教程?他們都應該涵蓋成員變量。成員變量是C#的基礎。 –

回答

2

_top聲明中Main,所以它不會有topToken方法內的知名度。這是一個局部變量,僅限於Main

爲了讓您的變量對整個類的可見性,您需要在任何方法之外聲明它們。

例:

public class SomeClass 
{ 
    public int someVariable; // all methods in SomeClass can see this 

    public void DoIt() { 
     // we can use someVariable here 
    } 
} 

注意,通過makeing someVariable公衆,這也意味着其他的我們可以直接訪問它。例如:

SomeClass x = new SomeClass(); 
x.someVariable = 42; 

如果你想防止這種情況,只允許methods/properties/etc。的類能夠看到someVariable變量,你可以聲明它是私有的。

在你需要一個公共變量的情況下,通常最好聲明一下這樣的(這是一個auto-implemented property)一個例子:

public class SomeClass 
{ 
    public int SomeVariable { get; set; } 

    public void DoIt() { 
     // we can use SomeVariable here 
    } 
} 

它使用

+0

將_top的定義移動到任何方法之外,但是在課程範圍之內... –

+0

好吧,我明白了,但是它應該到哪裏去呢?它必須能夠在全班同時公開訪問。 – Adam

+0

看到我添加的例子,我希望它有幫助。 – dcp

0

你的代碼改成這樣:

const int _top = 0; 

static void Main(string[] args) 
    { 
    ... 
    } 
public string[] topToken() 
    { 
     if (_top < _tokens.Count()) 
     { return _tokens[_top];} 

爲了讓_top整個類訪問,你必須把它聲明爲一個領域或一個常數。一個字段需要實際STO而常量則被編譯器的實際值所替代。正如你所描述的_top一樣,我決定宣佈它。

如果你需要一個領域,而不是一個常數,你必須聲明它static,因爲它是一個靜態方法訪問:

static int _top = 0; 

因爲有在_top聲明沒有publicprotected這是私人去上課。如果您願意,您可以在聲明前添加private,但如果缺少可見性,這將是默認設置。如果你想_topMain方法外可用

0

,這裏把它:

int _top = 0; //here instead 
static void Main(string[] args) 
{ 
    ... 
} 
public string[] topToken() 
{ 
    if (_top < _tokens.Count()) 
    { return _tokens[_top];} 
} 
相關問題