using System.ComponentModel; using System.Reflection; using Pf2e.Database.Model; using Pf2e.Database.Model.Base; using Pf2e.Database.Model.Enum; namespace Pf2e.Database; /// /// Аттрибут, указывающий тип сущности. /// /// Тип сущности. [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( $"'EntityOfTypeAttribute' attribute should only be applied to children of 'IEntity' class. '{type.FullName}' is not." ); } EntityOfTypeAttribute attribute = type.GetCustomAttribute()!; if (attribute.Type == entity.Type) { return type; } } throw new InvalidEnumArgumentException( $"Can't resolve class associated with '{entity.Type}' EntityType." ); } }