今天我遇到了一些问题,我写了一些代码并且真的不知道我哪里出错了,我会保持简短和甜蜜基本上Faze类中的GetServer()方法返回null并且我是真的不确定为什么,但我希望你们可以帮助我。
我在问题中涉及的每个类的下面都留下了一些代码片段,并且最初调用它的位置可以让您更好地了解出现问题的地方。
Program.cs入口点..
static void Main(string[] args)
{
XmlConfigurator.Configure();
Faze.run();
while (true)
Console.ReadKey();
}
Faze class
public static class Faze
{
private static FazeServer fazeServer;
public static void run()
{
Console.Title = "Loading...";
fazeServer = new FazeServer("");
}
public static FazeServer GetServer()
{
return fazeServer;
}
}
FazeServer类
public sealed class FazeServer
{
private ConsoleWorker consoleWorker;
public FazeServer(string lol)
{
LoadServer();
}
private void LoadServer()
{
consoleWorker = new ConsoleWorker();
classLogger.Info("Server has been loaded.");
}
}
ConsoleWorker类
class ConsoleWorker : IDisposable
{
private readonly Timer consoleWorkerTimer;
private readonly int consoleWorkerInterval;
private static ILog classLogger;
public ConsoleWorker()
{
if (Faze.GetServer() == null)
throw new Exception("Server null..");
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
consoleWorkerTimer = new Timer(TimerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
}
private void TimerElapsed(object timerObject)
{
// Do something...
}
public void Dispose()
{
consoleWorkerTimer.Dispose();
}
}
跟踪跟踪后,中断它的代码是我的空检查
if (Faze.GetServer() == null)
throw new Exception("Server null..");
在我添加if语句之前,导致异常的行是
consoleWorkerInterval = int.Parse(Faze.GetServer().GetConfig().GetConfigElement("console.worker.interval"));
为什么GetServer()返回null,有人可以帮忙吗?
答案 0 :(得分:0)
我正在喝几杯啤酒,但在课堂上#Faze'你已经实现了一个静态字段:' fazeServer'并没有为它赋值 - 因此它是null。 如果您想为' fazeServer'分配值?静态字段请在示例中实现类的静态构造函数' Faze' - 例如:' static Faze(){fazeServer = new FazeServer(" whatEverString");}'
那应该解决NRE。
此致
P.Sz。
答案 1 :(得分:0)
默认情况下,类字段初始化为 null ,因此您的代码相当于:
public static class Faze
{
private static FazeServer fazeServer = null;
public static FazeServer GetServer() => fazeServer;
}
当然,调用 GetServer()会返回未标记的值 null 。
如果您想自己初始化它,请使用静态构造函数:
public static class Faze
{
private static FazeServer fazeServer;
static Faze()
{
fazeServer = new FazeServer("");
}
}
或字段初始值设定项:
public static class Faze
{
private static FazeServer fazeServer = new FazeServer("");
}
因此,当您致电 GetServer()时,您肯定会得到一个实例。
答案 2 :(得分:0)
在GetServer()
静态变量中设置值之前,您正在调用fazeServer
。
调用堆栈如下:
fazeServer =新的FazeServer("");
- LoadServer();
- - consoleWorker = new ConsoleWorker();
- - - if(Faze.GetServer()== null)
或者,用简单的英语:
fazeServer
设置为new FazeServer()
new FazeServer()
内部调用LoadServer()
LoadServer()
内部调用new ConsoleWorker()
new ConsoleWorker()
内部调用Faze.GetServer()
Faze.GetServer()
返回fazeServer
因此设置该静态变量的代码在内部尝试读取该静态变量,然后才能完成设置。