2014-09-19 56 views
0

如何從另一個類訪問變量而不重構它?C#從另一個類訪問變量而不重構類

級#1:

namespace Server.world 
{ 
    public class WorldData 
    { 
     private entitys.Player[] Players = new entitys.Player[Convert.ToInt16(ConfigurationManager.AppSettings["maxplayers"])]; 

     public entitys.Player this[int i] 
     { 
      get { return Players[i]; } 
      set { Players[i] = value; } 
     } 
    } 
} 

類#2:構建worldData類:

namespace Server 
{ 
    class StartUp 
    { 
     public Server.tcpserver.TcpServer ListenerTcp = new Server.tcpserver.TcpServer(); 
     public world.WorldData WorldData = new world.WorldData(); 

     /// <summary> 
     /// Server start function 
     /// </summary> 
     public void Start() 
     { 
      string rootFolder = ConfigurationManager.AppSettings["rootfolder"]; 

      if (!Directory.Exists(rootFolder)) 
      { 
       Directory.CreateDirectory(rootFolder); 
       string pathString = Path.Combine(rootFolder, "world"); 
       Directory.CreateDirectory(pathString); 
      } 

      ListenerTcp.StartListening(); 
      //No code below this point 
     } 
    } 
} 

類#3:

namespace Server.tcpserver 
{ 
    class TcpServer 
    { 
     int counter = 0; 

     public void StartListening() 
     { 
      IPAddress ipAddress = Dns.GetHostEntry("127.0.0.1").AddressList[0]; 
      TcpListener serverSocket = new TcpListener(8888); 
      TcpClient clientSocket = default(TcpClient); 

      serverSocket.Start(); 
      counter = 0; 

      while (true) 
      { 
       counter += 1; 

       clientSocket = serverSocket.AcceptTcpClient(); 
       Server.client.Client Client = new Server.client.Client(clientSocket); 
       Console.WriteLine("Player Connected!"); 
       //get world playerdata here 
      } 
     } 
    } 
} 

我會怎麼做呢?我看到處處都找不到它

+0

你在哪裏實例化類3?你可以在構造函數中傳入你的'WorldData'對象。你可以在你的類中實例化它3 – paqogomez 2014-09-19 20:11:22

+0

類「StartUp」和「Class3」是如何相互關聯的? – 2014-09-19 20:11:35

+0

只有將該類轉換爲「靜態」,纔可以訪問成員而無需安裝 – 2014-09-19 20:11:38

回答

1

一種方法是,您可以提供一個構造函數,它使用WorldData的實例或者將WorldData作爲屬性公開的StartUp實例。

public class TcpServer 
{ 
    int counter = 0; 
    private StartUp startUp: 

    public TcpServer(StartUp startUp) 
    { 
     this.startUp = startUp; 
    } 

    public void StartListening() 
    { 
     // ... 
     var worldData = this.startUp.WorldData;  // <--- !!! 
     // ... 
    } 

    // ... 
} 

現在我也將使用的StartUp構造函數初始化TcpServer

public class StartUp 
{ 
    public StartUp() 
    { 
     WorldData = new world.WorldData(); 
     ListenerTcp = new Server.tcpserver.TcpServer(this); // <--- !!! 
    } 

    public Server.tcpserver.TcpServer ListenerTcp; 
    public world.WorldData WorldData; 
    // ... 
} 
+0

感謝這看起來像一個乾淨的解決方案,但如何使包含數組的靜態類? – 2014-09-19 20:34:26

+0

@StijnBernards:你爲什麼想這麼做?你想只支持一個世界嗎?一個靜態類只能包含靜態成員,這當然不是你想要的。 – 2014-09-19 20:41:49

+0

那麼我想要1個worldData類包含所有玩家數據和多個Levelclasses。我正在使用WorldData類,比如呃......那麼我保留其他類需要編輯的所有公共變量的文件。 – 2014-09-19 20:50:19