C#从另一个类访问变量而不重构类
如何从另一个类访问变量而不重构它?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
}
}
}
}
我会怎么做呢?我看到处处都找不到它
一种方法是,您可以提供一个构造函数,它使用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;
// ...
}
感谢这看起来像一个干净的解决方案,但如何使包含数组的静态类? – 2014-09-19 20:34:26
@StijnBernards:你为什么想这么做?你想只支持一个世界吗?一个静态类只能包含静态成员,这当然不是你想要的。 – 2014-09-19 20:41:49
那么我想要1个worldData类包含所有玩家数据和多个Levelclasses。我正在使用WorldData类,比如呃......那么我保留其他类需要编辑的所有公共变量的文件。 – 2014-09-19 20:50:19
你在哪里实例化类3?你可以在构造函数中传入你的'WorldData'对象。你可以在你的类中实例化它3 – paqogomez 2014-09-19 20:11:22
类“StartUp”和“Class3”是如何相互关联的? – 2014-09-19 20:11:35
只有将该类转换为“静态”,才可以访问成员而无需安装 – 2014-09-19 20:11:38