First, why Dictionary<TKey, TValue> does not support one blank key?
Secondly, is there an existing collection similar to a dictionary?
I want to keep System.Type "empty" or "missing" or "default", I thought that null would work well for this.
In particular, I wrote this class:
class Switch { private Dictionary<Type, Action<object>> _dict; public Switch(params KeyValuePair<Type, Action<object>>[] cases) { _dict = new Dictionary<Type, Action<object>>(cases.Length); foreach (var entry in cases) _dict.Add(entry.Key, entry.Value); } public void Execute(object obj) { var type = obj.GetType(); if (_dict.ContainsKey(type)) _dict[type](obj); } public static void Execute(object obj, params KeyValuePair<Type, Action<object>>[] cases) { var type = obj.GetType(); foreach (var entry in cases) { if (entry.Key == null || type.IsAssignableFrom(entry.Key)) { entry.Value(obj); break; } } } public static KeyValuePair<Type, Action<object>> Case<T>(Action action) { return new KeyValuePair<Type, Action<object>>(typeof(T), x => action()); } public static KeyValuePair<Type, Action<object>> Case<T>(Action<T> action) { return new KeyValuePair<Type, Action<object>>(typeof(T), x => action((T)x)); } public static KeyValuePair<Type, Action<object>> Default(Action action) { return new KeyValuePair<Type, Action<object>>(null, x => action()); } }
To include types. There are two ways to use it:
- Statically. Just call
Switch.Execute(yourObject, Switch.Case<YourType>(x => x.Action())) - precompiled. Create a switch and then use it later
switchInstance.Execute(yourObject)
It works fine if you do not try to add the default case to the "precompiled" version (exception from the null argument).
c #
mpen Jan 08 2018-11-11T00: 00Z
source share