2016-12-01 12 views
-5
namespace SnakesAndLadders 
{ 

    class Node 
    { 
     int snakeHead ; // points to another node where the player goes down to 
     int ladderFoot; // points to another node where to player goes up to 
    } 

    class Program 
    { 
     Node[] gameBoard = new Node[100]; 

     void loadStructure() 
     { 
      // first, set all the snakeheads and ladderFoots to zero 
      for (int i =0; i < 100; i++) 
      { 
       gameBoard[i].snakeHead = 0; 
       gameBoard[i].ladderFoot = 0; 
      } 
     } 
     static void Main(string[] args) 
     { 
     } 
    } 

在C#中,這不起作用。對於gameBoard [i],intellisense並未顯示它具有蛇頭組件。爲什麼不能像C++中的結構那樣訪問C#中的類的某些部分?

+4

'snakeHead'是一個私有字段.. – stuartd

+0

默認情況下,除非字面上聲明爲'public',否則所有類都是'private',其成員變量也是如此。 – MethodMan

回答

2

在類的C#字段默認

class Node 
{ 
    public int snakeHead ; // points to another node where the player goes down to 
    public int ladderFoot; // points to another node where to player goes up to 
} 

只是讓你的領域公衆應該解決您的問題私有。 編輯:使用最佳實踐,你會保持字段私人,但創建屬性,並使用它們來處理您的數據。還命名的私人用下劃線是一個常見的做法:

class Node 
{ 
    private int _snakeHead ; // points to another node where the player goes down to 
    public int SnakeHead 
    { 
     get {return _snakeHead;} 
     set {_snakeHead = value;} 
    } 

    private int _ladderFoot; // points to another node where to player goes up to 
    public int LadderFoot 
    { 
     get {return _ladderFoot;} 
     set {_ladderFoot = value;} 
    } 
} 
+2

僅供參考。類的聲明不正確。默認情況下,頂級類不是「私人」,而是「內部」。你寫的內容適用於嵌套類。 –

+1

你是對的,在C#類成員默認訪問修飾符是私有的,但類默認訪問修飾符是內部非私有。順便說一句,使用公共領域是一個很糟糕的做法,打破封裝,在這些情況下應該首選屬性。 – YuvShap

+0

謝謝@SomeUser – Roman

0

默認訪問修飾符是private。創建屬性以訪問您的私人字段。

class Node 
{ 
    int snakeHead ; // points to another node where the player goes down to 
    int ladderFoot; // points to another node where to player goes up to 

    public int SnakeHead 
    { 
     get { return snakeHead;} 
     set { snakeHead = value;} 
    } 

    public int LadderFoot 
    { 
     get { return ladderFoot; } 
     set { ladderFoot = value;} 
    } 
} 

之後,你可以gameBoard[i].SnakeHead = 0;

你甚至可以定義屬性是這樣的:

public int SnakeHead{get; set;} 

在這種情況下,你甚至不需要私人領域。

2

回答你的問題:結構的
在C++領域是public默認

在結構的C#字段private默認

您已經聲明沒有訪問修飾符關鍵字字段(private. public`)所以他們有上面提到的默認訪問。

爲了獲得在C#中相同的行爲,你需要聲明的訪問修飾符明確

struct Node 
{ 
    public int snakeHead ;to 
    public int ladderFoot; 
} 

請注意,在C++的類字段默認private

相關問題