C#从另一个类访问变量,而不重构该类
本文关键字:重构 变量 另一个 访问 | 更新日期: 2023-09-27 18:22:39
如何从另一个类访问变量而不重建它?
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
}
}
}
}
我该怎么做?我到处找都找不到,
一种方法是,您可以提供一个构造函数,该构造函数接受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;
// ...
}