我为Unity编译了一个.dll,其中包含多个组件。 其中之一是记录器,它会写入文件。但是为了在Unity中进行调试,我想添加一个将Log重定向到Function的委托。此功能在Unity中分配。但是,即使分配正确,也可以在dll端取消分配委托。 我想知道这是否与C#7.2与Mono 4.5有关。
无论如何,这是dll的代码。
public delegate void LoggerCallback(string log);
/// <summary>
/// Class that provides an interface to write logs to a file
/// </summary>
public static class ShatNetLogger
{
/// <summary>
/// Logger that writes network access to file
/// </summary>
///
private static LoggerCallback onLogEvent;
/// <summary>
/// The event that gets fired when log occurs
/// </summary>
public static LoggerCallback OnLogEvent { get => onLogEvent; set => onLogEvent = value; }
/// <summary>
/// The Callback that gets triggered when a user connected to this instance
/// </summary>
static Mutex writeLock = new Mutex();
static bool isInit;
/// <summary>
/// Is the logger initialized
/// </summary>
public static bool IsInit { get => isInit; }
static DebugLevel debugLevel;
static string fileName = "/netlog.log";
static string location = "";
/// <summary>
/// Initializes the logger
/// </summary>
/// <param name="dLevel"></param>
/// <param name="path"></param>
public static void InitLogger(DebugLevel dLevel, string path)
{
writeLock.WaitOne();
//If the logger is open already, do nothing
if (IsInit)
{
}
else
{
isInit = true;
location = path;
debugLevel = dLevel;
if (Directory.Exists(location))
{
if (File.Exists(location + fileName))
{
}
else
{
try
{
File.Create(location + fileName);
}
catch (IOException ioE)
{
}
}
}
else
{
Directory.CreateDirectory(location);
File.Create(location + fileName);
}
}
writeLock.ReleaseMutex();
Log("Log Session opened at" + location + fileName);
}
/// <summary>
/// Log byte array to file if selected loglevel allows it
/// </summary>
/// <param name="log"></param>
/// <param name="level">The level to use, default is any(info)</param>
/// [
///
[Obsolete("Use Log<T> Instead which accepts any base type")]
public static void LogRaw(byte[] log, DebugLevel level = DebugLevel.Info)
{
//Debuglevel is lower than required for printing
if (level > debugLevel)
{
}
else
{
using (StreamWriter sWriter = new StreamWriter(location + fileName, true))
{
sWriter.WriteLine("[" + level.ToString() + "]" + log + " | " + DateTime.Now.ToLongTimeString());
}
if (OnLogEvent != null)
{
OnLogEvent?.Invoke("[" + level.ToString() + "]" + log + " | " + DateTime.Now.ToLongTimeString());
ShatNetLogger.Log("Calling " + OnLogEvent.Method.Name);
}
else
{
}
}
}
这是Unity部分,作用不大。
public void Start()
{
ShatNetNetwork.StartListenServer();
ShatNetLogger.OnLogEvent += Log;
}
void Update()
{
}
void OnApplicationQuit()
{
ShatNetNetwork.Close();
Debug.Log("API Shutdown");
}
public void Log(string log)
{
Debug.Log(log);
}