Files
Pf2eDataScrapper/Pf2eModel/EntityOfTypeAttribute.cs

57 lines
1.9 KiB
C#

using System.ComponentModel;
using System.Reflection;
using Pf2eModel.Model;
using Pf2eModel.Model.Base;
using Pf2eModel.Model.Enum;
namespace Pf2eModel;
/// <summary>
/// Аттрибут, указывающий тип сущности.
/// </summary>
/// <param name="type">Тип сущности.</param>
[AttributeUsage(AttributeTargets.Class)]
public class EntityOfTypeAttribute(EntityType type) : Attribute
{
/// <summary>
/// Тип сущности.
/// </summary>
public EntityType Type { get; } = type;
/// <summary>
/// Метод для получения программного типа сущности по её типу.
/// </summary>
/// <param name="entity">Тип сущности.</param>
/// <returns>Программный тип сущности.</returns>
/// <exception cref="Exception">Если есть ошибка в структурах.</exception>
/// <exception cref="InvalidEnumArgumentException">Тип сущности.</exception>
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(
$"'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 InvalidEnumArgumentException(
$"Can't resolve class associated with '{entity.Type}' EntityType."
);
}
}