Guest User

Untitled

a guest
Jul 29th, 2012
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. What is the best method for attaching a single key/value pair attribute to an enumeration?
  2. [AttributeUsage(AttributeTargets.Field)]
  3. public class MerchantDataAttribute : Attribute
  4. {
  5. public MerchantDataAttribute(string merchantId, string transactionId)
  6. {
  7. this.MerchantId = merchantId;
  8. this.TransactionId = transactionId;
  9. }
  10.  
  11. public string MerchantId
  12. {
  13. get;
  14. private set;
  15. }
  16.  
  17. public string TransactionId
  18. {
  19. get;
  20. private set;
  21. }
  22. }
  23.  
  24. public static class MerchantsExtensions
  25. {
  26. private static readonly Dictionary<Merchants, MerchantDataAttribute>
  27. _merchantsCache = CacheMerchantsCache();
  28.  
  29. public static string GetMerchantId(this Merchants merchants)
  30. {
  31. return _merchantsCache[merchants].MerchantId;
  32. }
  33.  
  34. public static string GetTransactionId(this Merchants merchants)
  35. {
  36. return _merchantsCache[merchants].TransactionId;
  37. }
  38.  
  39. private static Dictionary<Merchants, MerchantDataAttribute> CacheMerchantsCache()
  40. {
  41. return Enum.GetValues(typeof(Merchants))
  42. .Cast<Merchants>()
  43. .Select(m => new
  44. {
  45. Merchant = m,
  46. MerchantAttribute = GetMerchantAttribute(m)
  47. })
  48. .ToDictionary(m => m.Merchant, m => m.MerchantAttribute);
  49. }
  50.  
  51. private static MerchantDataAttribute GetMerchantAttribute(Merchants merchant)
  52. {
  53. return typeof(Merchants)
  54. .GetMember(merchant.ToString())
  55. .First()
  56. .GetCustomAttributes(typeof(MerchantDataAttribute), inherit: false)
  57. .Cast<MerchantDataAttribute>()
  58. .First();
  59. }
  60. }
  61.  
  62. Public Class Merchants
  63. Public Shared ReadOnly Property Coke() As Merchant
  64. Get
  65. Return _coke
  66. End Get
  67. End Property
  68. Private Shared _coke = New Merchant(0, "Coke", "faj80785hq+faf=-1=-jfa+")
  69.  
  70. ...
  71. End Class
Advertisement
Add Comment
Please, Sign In to add comment