PkmnLib.NET/PkmnLib.Dynamic/ScriptHandling/Registry/ScriptUtils.cs

33 lines
1.1 KiB
C#
Raw Normal View History

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));
/// <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;
}
}