我有一个项目,其中一个主要方法是返回null,因为很清楚我已经为它分配了一个值。
的Program.cs:
using System;
namespace Sahara
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Title = "Loading Sahara...";
Console.CursorVisible = false;
Sahara.Initialize();
while (true)
{
Console.ReadKey();
}
}
}
}
Sahara.cs:
namespace Sahara
{
class Sahara
{
private static SaharaServer server;
public static void Initialize()
{
server = new SaharaServer();
}
public static SaharaServer GetServer()
{
return server;
}
}
}
SaharaServer:
using Sahara.Core.Config;
using Sahara.Core.Logging;
using Sahara.Core.Server;
using System;
using System.Diagnostics;
namespace Sahara
{
class SaharaServer
{
private readonly ServerStatusUpdater serverStatusUpdater;
private readonly LogManager logManager;
private readonly ServerInformation serverInformation;
private readonly DateTime startedTime;
private readonly ConfigManager configManager;
public SaharaServer()
{
logManager = new LogManager();
serverInformation = new ServerInformation();
foreach (string consoleOutputString in serverInformation.ConsoleLogo)
{
Console.WriteLine(consoleOutputString);
}
logManager.Log("Loading " + serverInformation.ServerName + "...", LogType.Information);
Stopwatch stopwatch = Stopwatch.StartNew();
configManager = new ConfigManager("Extra/Other/config.ini");
startedTime = DateTime.Now;
serverStatusUpdater = new ServerStatusUpdater();
stopwatch.Stop();
logManager.Log("Finished Loading! [" + stopwatch.ElapsedMilliseconds + "ms]", LogType.Warning);
Console.ForegroundColor = ConsoleColor.Black;
}
public LogManager GetLogManager()
{
return logManager;
}
public ServerInformation GetServerInformation()
{
return serverInformation;
}
public DateTime StartedTime
{
get { return startedTime; }
}
public ConfigManager GetConfigManager()
{
return configManager;
}
public void Dispose()
{
try
{
serverStatusUpdater.Dispose();
}
catch (Exception exception)
{
if (logManager != null)
{
logManager.Log("Error in disposing SaharaServer: " + exception.Message, LogType.Error);
logManager.Log(exception.StackTrace, LogType.Error);
}
}
finally
{
Environment.Exit(0);
}
}
}
}
但是为什么Sahara.cs中的GetServer()返回null !!?!?!?!?
答案 0 :(得分:3)
您从ConfigManager
构造函数中调用SaharaServer
构造函数,因此构造函数尚未完成设置server
字段,因此GetServer
将返回{{1} }}