using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Spine.Utils
{
///
/// 提供关联的实现标识
///
/// 标记类型
public interface IImplementationKeyAttribute
{
///
/// 实现类类型标记
///
TKey ImplementationKey { get; }
}
///
/// 可以使用反射查找基类关联的所有实现类
///
/// 所有实现类的基类型
/// 实现类类型属性标记类型
/// 实现类类型标记类型
public abstract class ImplementationResolver
where TAttr : Attribute, IImplementationKeyAttribute
where TKey : notnull
{
///
/// 实现类型缓存
///
private static readonly Dictionary _implementationTypes = [];
static ImplementationResolver()
{
var baseType = typeof(TBase);
var impTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => baseType.IsAssignableFrom(t) && !t.IsAbstract);
foreach (var type in impTypes)
{
foreach (var attr in type.GetCustomAttributes())
{
var key = attr.ImplementationKey;
if (_implementationTypes.ContainsKey(key))
throw new InvalidOperationException($"Multiple implementations found for key: {key}");
_implementationTypes[key] = type;
}
}
}
///
/// 判断某种类型是否实现
///
public static bool HasImplementation(TKey key) => _implementationTypes.ContainsKey(key);
///
/// 根据实现类键和参数创建实例
///
///
///
///
///
protected static TBase CreateInstance(TKey impKey, params object?[]? args)
{
if (!_implementationTypes.TryGetValue(impKey, out var type))
throw new NotImplementedException($"Not implemented type for {typeof(TBase)}: {impKey}");
return (TBase)Activator.CreateInstance(type, args);
}
}
}