2014-08-28 117 views
0

我最近一直用C#擺弄周圍,所遇到的一個問題:私有類成員與方法返回類型爲

我有四類:

  • 方案:與主要方法。
  • 遊戲:一切都發生的地方。
  • 實體:基本實體類。
  • 播放器:從實體衍生

(無論實體和玩家都是遊戲類中)現在

,我的問題是,這是更好:

  1. 要使玩家在我的遊戲類中的私人對象,並使用一些公共方法訪問所述對象,或者...

  2. 若要製作一些公共方法並返回新玩家對象從那些被整個班級訪問?

這可能是嚴重的解釋,所以這裏有一個例子:

爲1:

namespace Test 
{ 
    class Game 
    { 
     public Game() 
     { 
      createChar(); 
     } 
     private Player player; 

     public class Entity 
     { 
      public string type; 
     } 
     public class Player : Entity 
     { 
      public string name; 
     } 

     private void createChar() 
     { 
      player = new Player(); 

      Console.WriteLine("What type of being is your character?"); 
      player.type = Console.ReadLine(); 
      Console.WriteLine("Name your character."); 
      player.name = Console.ReadLine(); 
      Console.WriteLine(); 
     } 

     public void run() 
     { 
      Console.WriteLine("Your character's name is:"); 
      Console.WriteLine(player.name); 
     } 
    } 

    class Program 
    { 
     public static void Main(string[] args) 
     { 
      Game game = new Game(); 
      game.run(); 
     } 
    } 
} 

爲2:

namespace Test 
{ 
    class Game 
    { 
     public class Entity 
     { 
      public string type; 
     } 
     public class Player : Entity 
     { 
      public string name; 
     } 

     public Player createChar() 
     { 
      Player player = new Player(); 

      Console.WriteLine("What type of being is your character?"); 
      player.type = Console.ReadLine(); 
      Console.WriteLine("Name your character."); 
      player.name = Console.ReadLine(); 
      Console.WriteLine(); 

      return player; 
     } 

     public void run(Player player) 
     { 
      Console.WriteLine("Your character's name is:"); 
      Console.WriteLine(player.name); 
     } 
    } 

    class Program 
    { 
     public static void Main(string[] args) 
     { 
      Game game = new Game(); 
      Game.Player player = game.createChar(); 
      game.run(player); 
     } 
    } 
} 

這個問題是不應該開放式結束,我道歉,如果它似乎是,但爲了讓我的問題更具體一點,這裏是我所關心的所有問題的列表g此代碼:

  1. 哪個程序更好1.或2.?
  2. 哪個程序更具可擴展性?
  3. 有沒有更好的方法來編寫程序?
  4. 我是否錯過了應該被問到的任何問題?

此外,請忽略類Entity和Player的空虛。

+3

請使用2 - 將'class Game'變成一個靜態類並從中提取'Player'(爲什麼要嵌套這些?) – Carsten 2014-08-28 16:23:58

+1

請看[關於組件中嵌套類的建議](http:// msdn。微軟。COM/EN-US /庫/ s9f3ty7f(V = vs.71)的.aspx)。 – 2014-08-28 16:25:15

+0

這個問題似乎無關緊要,因爲它涉及到代碼審查。 – BradleyDotNET 2014-08-28 16:29:27

回答

0

選項二聽起來更好,因爲在Game類中需要的代碼較少(您不需要用於Game的用戶類能夠訪問的每一段數據的方法),並且它更靈活(更改到Player類不需要修改Game類中的方法)。

我可以看到選擇1的唯一原因是,如果您有另一個類直接訪問有關Player對象的數據(因此無需通過Game類),並且該數據真的不應該被訪問使用Game類訪問玩家數據的類,因此證明Game中的方法只允許用戶類的Game訪問Player中的某些數據。

相關問題