Skip to content

Instantly share code, notes, and snippets.

@marihachi
Last active February 2, 2016 10:17
Show Gist options
  • Save marihachi/5c0650534e9de0e8bb3c to your computer and use it in GitHub Desktop.
Save marihachi/5c0650534e9de0e8bb3c to your computer and use it in GitHub Desktop.
switch文のcase内での変数のスコープが気持ちが悪かったので、変わりとなるものを作ってみたけど使い方がスマートでないので結局使わなかった。なのでせめてここに残しておきます。
using System;
using System.Collections.Generic;
public class Switch<T>
{
public Switch(T target)
{
Target = target;
}
public Switch(T target, Dictionary<T, Action> cases)
{
Target = target;
foreach (var i in cases)
Case(i.Key, i.Value);
}
public Switch(T target, Action defaultCase)
{
Target = target;
_DefaultCase = defaultCase;
}
public Switch(T target, Dictionary<T, Action> cases, Action defaultCase)
{
Target = target;
foreach (var i in cases)
Case(i.Key, i.Value);
_DefaultCase = defaultCase;
}
public T Target { get; private set; }
public Dictionary<T, Action> Cases { get; set; } = new Dictionary<T, Action>();
private Action _DefaultCase { get; set; }
public void Case(T value, Action callback)
{
foreach (var i in Cases)
if (i.Key.Equals(value))
throw new ArgumentException($"'{value}'というケースはこのインスタンスに既に追加されています。");
Cases.Add(value, callback);
}
public void DefaultCase(Action callback)
{
_DefaultCase = callback;
}
public void Call()
{
foreach(var i in Cases)
if (i.Key.Equals(Target))
{
i.Value();
return;
}
_DefaultCase();
}
}
public static class Sample
{
public static void Main()
{
string str = "hoge";
var s = new Switch<string>(str);
s.Case("hoge", () =>
{
Console.WriteLine("Hoge");
});
s.Case("piyo", () =>
{
Console.WriteLine("Piyo");
});
s.Call();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment