code_junkie

Fallback accessors in C#

Nov 14th, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. class Foo
  2. {
  3. protected bool Get(string name, bool def)
  4. {
  5. try {
  6. return client.Get(name);
  7. } catch {
  8. return def;
  9. }
  10. }
  11.  
  12. public bool Bar
  13. {
  14. get { return Get("bar", true); }
  15. set { client.Set("bar", value); }
  16. }
  17.  
  18. public bool Baz
  19. {
  20. get { return Get("baz", false); }
  21. set { client.Set("baz", value); }
  22. }
  23. }
  24.  
  25. class Foo
  26. {
  27. public bool Get(string name)
  28. {
  29. try {
  30. return client.Get(name);
  31. } catch {
  32. // Look-up default value in hash table and return it
  33. }
  34. }
  35.  
  36. public void Set(string name, object value)
  37. {
  38. client.Set(name, value)
  39. }
  40. }
  41.  
  42. class my_class:
  43. pass
  44.  
  45. my_instance = my_class()
  46. my_instance.my_attr = 1
  47. print(my_instance.my_attr)
  48.  
  49. protected T Get<T>(string name, T @default)
  50. {
  51. var prop = GetType().GetProperty(name);
  52. if(prop == null) return @default;
  53. return (T) prop.GetValue(this, null);
  54. }
  55.  
  56. using System;
  57. using System.Collections.Generic;
  58.  
  59. namespace Program
  60. {
  61. class Program
  62. {
  63. static void Main(string[] args)
  64. {
  65. MyList<int> list = new MyList<int>();
  66. // Add a property with setter.
  67. list["One"] = 1;
  68. // Add a property with getter which takes default value.
  69. int two = list["Two", 2];
  70. Console.WriteLine("One={0}", list["One"]);
  71. Console.WriteLine("Two={0} / {1}", two, list["Two"]);
  72. try
  73. {
  74. Console.WriteLine("Three={0}", list["Three"]);
  75. }
  76. catch
  77. {
  78. Console.WriteLine("Three does not exist.");
  79. }
  80. }
  81. class MyList<T>
  82. {
  83. Dictionary<string, T> dictionary = new Dictionary<string,T>();
  84.  
  85. internal T this[string property, T def]
  86. {
  87. get
  88. {
  89. T value;
  90. if (!dictionary.TryGetValue(property, out value))
  91. dictionary.Add(property, value = def);
  92. return value;
  93. }
  94. }
  95. internal T this[string property]
  96. {
  97. get
  98. {
  99. return dictionary[property];
  100. }
  101. set
  102. {
  103. dictionary[property] = value;
  104. }
  105. }
  106. }
  107. }
  108. }
Add Comment
Please, Sign In to add comment