Skip to content

Instantly share code, notes, and snippets.

@phatty
Created March 25, 2013 01:47
Show Gist options
  • Save phatty/5234429 to your computer and use it in GitHub Desktop.
Save phatty/5234429 to your computer and use it in GitHub Desktop.
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