using System; using System.Linq; using System.Reflection; using Vanara.Extensions; namespace Vanara.PInvoke { /// Associates a Guid with an element. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Struct, AllowMultiple = true, Inherited = false)] public class AssociateAttribute : Attribute { /// Initializes a new instance of the class. /// A GUID. public AssociateAttribute(string guid) => Guid = new Guid(guid); /// Gets or sets the GUID associated with this element. /// A GUID value. public Guid Guid { get; } /// Retrieves the Guid associated with an enum value. /// An enum type. /// The enum value. /// The GUID associated with the or if no association exists. public static Guid GetGuidFromEnum(T value) => typeof(T).GetField(value.ToString())?.GetCustomAttributes().Select(a => a.Guid).FirstOrDefault() ?? Guid.Empty; /// Tries a lookup of the enum value associated with a Guid. /// The unique identifier. /// The found value. /// true if found. public static bool TryEnumLookup(Guid guid, out T value) { foreach (var f in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)) { if (f.GetCustomAttributes().All(a => a.Guid != guid)) continue; value = (T)f.GetRawConstantValue(); return true; } value = default; return false; } } }