Created
November 29, 2016 12:47
-
-
Save seralexeev/be1165ae1747f90f2dd29f9a32feb55e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
class Program { | |
public static void Main() { | |
var input = "12"; | |
using (new switchOf(input) { | |
(int a) => Console.WriteLine($"int: {a}"), | |
(string a) => Console.WriteLine($"string: {a}"), | |
}); | |
} | |
} | |
class switchOf : IEnumerable, IDisposable { | |
Dictionary<Type, Action<object>> _handlers = new Dictionary<Type, Action<object>>(); | |
object _obj; | |
public switchOf(object obj) { | |
_obj = obj; | |
} | |
public void Add<T> (Action<T> action) { | |
var type = typeof(T); | |
if(_handlers.ContainsKey(type)) | |
throw new InvalidOperationException(); | |
_handlers[type] = (object o) => action((T) o); | |
} | |
public void Dispose() { | |
var type = _obj.GetType(); | |
if (_handlers.TryGetValue(type, out var handler)) { | |
handler(_obj); | |
} | |
} | |
IEnumerator IEnumerable.GetEnumerator() => null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment