2024-08-10 07:44:46 +00:00
|
|
|
using System.Reflection;
|
|
|
|
using PkmnLib.Static.Utils;
|
|
|
|
|
|
|
|
namespace PkmnLib.Dynamic.ScriptHandling.Registry;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Extension methods for scripts.
|
|
|
|
/// </summary>
|
|
|
|
public static class ScriptUtils
|
|
|
|
{
|
|
|
|
private static readonly Dictionary<Type, StringKey> NameCache = new();
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Resolve name from the <see cref="ScriptAttribute"/> of the given script.
|
|
|
|
/// </summary>
|
|
|
|
public static StringKey ResolveName(this Script script) => ResolveName(script.GetType());
|
|
|
|
|
2024-11-02 11:59:55 +00:00
|
|
|
public static StringKey ResolveName<T>() where T : Script => ResolveName(typeof(T));
|
|
|
|
|
2024-08-10 07:44:46 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Resolve name from the <see cref="ScriptAttribute"/> of the given type.
|
|
|
|
/// </summary>
|
|
|
|
public static StringKey ResolveName(Type type)
|
|
|
|
{
|
|
|
|
if (NameCache.TryGetValue(type, out var name))
|
|
|
|
return name;
|
|
|
|
|
|
|
|
var scriptAttr = type.GetCustomAttribute<ScriptAttribute>();
|
|
|
|
if (scriptAttr == null)
|
|
|
|
throw new InvalidOperationException($"Type {type} does not have a {nameof(ScriptAttribute)}.");
|
|
|
|
return NameCache[type] = scriptAttr.Name;
|
|
|
|
}
|
|
|
|
}
|