在MSDN博客文章
很多问题:switch on type中,提供了关于为什么
.NET不提供类型切换的一些信息。
通常情况下,总会有解决方法。
这个解决方法不是我想出来的,但不幸的是我已经丢失了来源。它可以实现类型切换,但我个人认为它相当笨拙(使用字典的想法更好)。
public class Switch
{
public Switch(Object o)
{
Object = o;
}
public Object Object { get; private set; }
}
public static class SwitchExtensions
{
public static Switch Case<T>(this Switch s, Action<T> a)
where T : class
{
return Case(s, o => true, a, false);
}
public static Switch Case<T>(this Switch s, Action<T> a,
bool fallThrough) where T : class
{
return Case(s, o => true, a, fallThrough);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a) where T : class
{
return Case(s, c, a, false);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a, bool fallThrough) where T : class
{
if (s == null)
{
return null;
}
T t = s.Object as T;
if (t != null)
{
if (c(t))
{
a(t);
return fallThrough ? s : null;
}
}
return s;
}
}
使用方法:
new Switch(foo)
.Case<Fizz>
(action => { doingSomething = FirstMethodCall(); })
.Case<Buzz>
(action => { return false; })