Files
Fishing2Server/Entity/Modules/ConfigTable/ConfigTableHelper.cs
2025-11-11 17:43:11 +08:00

122 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
using Fantasy;
using Fantasy.Helper;
using Newtonsoft.Json.Linq;
// ReSharper disable SuspiciousTypeConversion.Global
namespace NBF.ConfigTable
{
/// <summary>
/// 配置表帮助类
/// </summary>
public static class ConfigTableHelper
{
private static readonly Dictionary<Type, IConfigContext> _dictionary = new Dictionary<Type, IConfigContext>();
public static void Initialize()
{
//解析配置文件
var gameConfigText = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "configs.Json"));
Initialize(gameConfigText, typeof(Fantasy.AssemblyHelper).Assembly);
}
/// <summary>
/// 初始化ConfigTableHelper
/// </summary>
public static void Initialize(string json, params System.Reflection.Assembly[] assemblies)
{
_dictionary.Clear();
var jsonObj = JObject.Parse(json);
Dictionary<string, JArray> tokens = new();
foreach (var item in jsonObj)
{
try
{
var name = item.Key;
var value = item.Value;
if (value is JArray jArray)
{
tokens[name] = jArray;
}
}
catch (Exception e)
{
Log.Error($"读表异常请检查name={item.Key} ex={e}");
}
}
foreach (var type in GetAllConfigTableTypes(assemblies))
{
var name = type.Name;
if (tokens.TryGetValue(name, out var jArray))
{
// 通过反射调用 ParseJson 方法
var parseMethod = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.Static);
parseMethod?.Invoke(null, [jArray]);
}
}
// var d = _dictionary;
}
public static ConfigContext<T>? Table<T>() where T : IConfigTable
{
var type = typeof(T);
if (_dictionary.TryGetValue(type, out var context))
{
return context as ConfigContext<T>;
}
var jsonContext = new ConfigContext<T>();
_dictionary[type] = jsonContext;
return jsonContext;
}
public static List<T> ParseLine<T>(JArray arr) where T : IConfigTable, new()
{
List<T> list = new List<T>();
foreach (var jToken in arr)
{
T? instance = jToken.ToObject<T>();
if (instance != null)
{
list.Add(instance);
}
}
var context = Table<T>();
context?.Association(list);
return list;
}
/// <summary>
/// 获取所有实现了 IConfigTable 接口的非抽象类
/// </summary>
/// <returns>所有非抽象的配置对象类</returns>
private static List<Type> GetAllConfigTableTypes(params System.Reflection.Assembly[] assemblies)
{
var types = new List<Type>();
var interfaceType = typeof(IConfigTable);
// 遍历当前程序集中的所有类型
foreach (var assembly in assemblies)
{
foreach (var type in assembly.GetTypes())
{
// 检查是否实现了 IConfigTable 接口,并且不是抽象类
if (interfaceType.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
{
types.Add(type);
}
}
}
return types;
}
}
}