Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Foo
- {
- protected bool Get(string name, bool def)
- {
- try {
- return client.Get(name);
- } catch {
- return def;
- }
- }
- public bool Bar
- {
- get { return Get("bar", true); }
- set { client.Set("bar", value); }
- }
- public bool Baz
- {
- get { return Get("baz", false); }
- set { client.Set("baz", value); }
- }
- }
- class Foo
- {
- public bool Get(string name)
- {
- try {
- return client.Get(name);
- } catch {
- // Look-up default value in hash table and return it
- }
- }
- public void Set(string name, object value)
- {
- client.Set(name, value)
- }
- }
- class my_class:
- pass
- my_instance = my_class()
- my_instance.my_attr = 1
- print(my_instance.my_attr)
- protected T Get<T>(string name, T @default)
- {
- var prop = GetType().GetProperty(name);
- if(prop == null) return @default;
- return (T) prop.GetValue(this, null);
- }
- using System;
- using System.Collections.Generic;
- namespace Program
- {
- class Program
- {
- static void Main(string[] args)
- {
- MyList<int> list = new MyList<int>();
- // Add a property with setter.
- list["One"] = 1;
- // Add a property with getter which takes default value.
- int two = list["Two", 2];
- Console.WriteLine("One={0}", list["One"]);
- Console.WriteLine("Two={0} / {1}", two, list["Two"]);
- try
- {
- Console.WriteLine("Three={0}", list["Three"]);
- }
- catch
- {
- Console.WriteLine("Three does not exist.");
- }
- }
- class MyList<T>
- {
- Dictionary<string, T> dictionary = new Dictionary<string,T>();
- internal T this[string property, T def]
- {
- get
- {
- T value;
- if (!dictionary.TryGetValue(property, out value))
- dictionary.Add(property, value = def);
- return value;
- }
- }
- internal T this[string property]
- {
- get
- {
- return dictionary[property];
- }
- set
- {
- dictionary[property] = value;
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment