Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- What is the best method for attaching a single key/value pair attribute to an enumeration?
- [AttributeUsage(AttributeTargets.Field)]
- public class MerchantDataAttribute : Attribute
- {
- public MerchantDataAttribute(string merchantId, string transactionId)
- {
- this.MerchantId = merchantId;
- this.TransactionId = transactionId;
- }
- public string MerchantId
- {
- get;
- private set;
- }
- public string TransactionId
- {
- get;
- private set;
- }
- }
- public static class MerchantsExtensions
- {
- private static readonly Dictionary<Merchants, MerchantDataAttribute>
- _merchantsCache = CacheMerchantsCache();
- public static string GetMerchantId(this Merchants merchants)
- {
- return _merchantsCache[merchants].MerchantId;
- }
- public static string GetTransactionId(this Merchants merchants)
- {
- return _merchantsCache[merchants].TransactionId;
- }
- private static Dictionary<Merchants, MerchantDataAttribute> CacheMerchantsCache()
- {
- return Enum.GetValues(typeof(Merchants))
- .Cast<Merchants>()
- .Select(m => new
- {
- Merchant = m,
- MerchantAttribute = GetMerchantAttribute(m)
- })
- .ToDictionary(m => m.Merchant, m => m.MerchantAttribute);
- }
- private static MerchantDataAttribute GetMerchantAttribute(Merchants merchant)
- {
- return typeof(Merchants)
- .GetMember(merchant.ToString())
- .First()
- .GetCustomAttributes(typeof(MerchantDataAttribute), inherit: false)
- .Cast<MerchantDataAttribute>()
- .First();
- }
- }
- Public Class Merchants
- Public Shared ReadOnly Property Coke() As Merchant
- Get
- Return _coke
- End Get
- End Property
- Private Shared _coke = New Merchant(0, "Coke", "faj80785hq+faf=-1=-jfa+")
- ...
- End Class
Advertisement
Add Comment
Please, Sign In to add comment