Created
March 25, 2013 01:47
-
-
Save phatty/5234429 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace CSP_PGP_Fileprocessor_util | |
{ | |
static class TypeSwitch | |
{ | |
public class CaseInfo { | |
public bool IsDefault { get; set; } | |
public Type Target { get; set; } | |
public Action<object> Action { get; set; } | |
} | |
public static void Do(Type source, params CaseInfo[] cases) | |
{ | |
var Type = source; | |
foreach (var entry in cases) | |
{ | |
if (entry.IsDefault || entry.Target.IsAssignableFrom(Type)) | |
{ | |
entry.Action(source); | |
break; | |
} | |
} | |
} | |
public static void Do(object source, params CaseInfo[] cases) | |
{ | |
var Type = source.GetType(); | |
foreach (var entry in cases) | |
{ | |
if (entry.IsDefault || entry.Target.IsAssignableFrom(Type)) | |
{ | |
entry.Action(source); | |
break; | |
} | |
} | |
} | |
public static CaseInfo Case<T>(Action action) | |
{ | |
return new CaseInfo() | |
{ | |
Action = x => action(), | |
Target = typeof(T) | |
}; | |
} | |
public static CaseInfo Case<T>(Action<T> action) | |
{ | |
return new CaseInfo() | |
{ | |
Action = (x) => action((T)x), | |
Target = typeof(T) | |
}; | |
} | |
public static CaseInfo Default(Action action) | |
{ | |
return new CaseInfo() | |
{ | |
Action = x => action(), | |
IsDefault = true | |
}; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment