114 lines
3.5 KiB
C#
114 lines
3.5 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Reflection;
|
||
using Newtonsoft.Json.Linq;
|
||
|
||
namespace NBC
|
||
{
|
||
/// <summary>
|
||
/// 配置表帮助类
|
||
/// </summary>
|
||
public static class ConfigTableHelper
|
||
{
|
||
private static readonly Dictionary<Type, IConfigContext> _dictionary = new Dictionary<Type, IConfigContext>();
|
||
|
||
/// <summary>
|
||
/// 初始化ConfigTableHelper
|
||
/// </summary>
|
||
public static void Initialize(string json)
|
||
{
|
||
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}");
|
||
}
|
||
}
|
||
|
||
//反射获取所有IConfigTable的非抽象类
|
||
var tableTypes = GetAllConfigTableTypes();
|
||
foreach (var type in tableTypes)
|
||
{
|
||
var name = type.Name;
|
||
if (tokens.TryGetValue(name, out var jArray))
|
||
{
|
||
// 通过反射调用 ParseJson 方法
|
||
var parseMethod = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.Static);
|
||
parseMethod?.Invoke(null, new object[] { jArray });
|
||
}
|
||
}
|
||
|
||
}
|
||
|
||
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()
|
||
{
|
||
var types = new List<Type>();
|
||
var interfaceType = typeof(IConfigTable);
|
||
|
||
// 遍历当前程序集中的所有类型
|
||
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||
{
|
||
foreach (var type in assembly.GetTypes())
|
||
{
|
||
// 检查是否实现了 IConfigTable 接口,并且不是抽象类
|
||
if (interfaceType.IsAssignableFrom(type) && !type.IsAbstract && !type.IsInterface)
|
||
{
|
||
types.Add(type);
|
||
}
|
||
}
|
||
}
|
||
|
||
return types;
|
||
}
|
||
}
|
||
} |