Files
Pf2eDataScrapper/Pf2eModel/EntityOfTypeAttribute.cs
T

40 lines
1.1 KiB
C#

using System.Reflection;
using Pf2eModel.Model;
using Pf2eModel.Model.Base;
using Pf2eModel.Model.Enum;
namespace Pf2eModel;
[AttributeUsage(AttributeTargets.Class)]
public class EntityOfTypeAttribute(EntityType type) : Attribute
{
public EntityType Type { get; } = type;
public static Type Resolve(Entity entity)
{
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.GetCustomAttributes(typeof(EntityOfTypeAttribute), true).Length <= 0)
{
continue;
}
if (!type.IsAssignableTo(typeof(IEntity)))
{
throw new Exception(
$"'EntityOfTypeAttribute' attribute should only be applied to children of 'IEntity' class. '{type.FullName}' is not."
);
}
EntityOfTypeAttribute attribute = type.GetCustomAttribute<EntityOfTypeAttribute>()!;
if (attribute.Type == entity.Type)
{
return type;
}
}
throw new Exception($"Can't resolve class associated with '{entity.Type}' EntityType.");
}
}