我从http://blogs.msdn.com/b/jaredpar/archive/2008/05/16/switching-on-types.aspx获取了以下代码
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(object source, params CaseInfo[] cases) {
var type = source.GetType();
foreach (var entry in cases) {
if (entry.IsDefault || type == entry.Target) {
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
};
}
}
我正在做以下事情
TypeSwitch.Do(
p.PropertyType,
TypeSwitch.Case<Int32>(() => DoSomething),
TypeSwitch.Case<Double>(() => DoSomething),
TypeSwitch.Case<float>(() => DoSomething),
TypeSwitch.Case<bool>(() => DoSomething),
TypeSwitch.Case<String>(() => DoSomething),
TypeSwitch.Default(() => {
TypeSwitch.Do
(
p.PropertyType,
TypeSwitch.Case<Object[]>(() => Do()),
TypeSwitch.Case<IEnumerable<Object>>(() => Do()),
TypeSwitch.Case<IDictionary<Object, Object>>(() => Do()
)
);
p 是类型PropertyInfo
。即使 p.PropertyType 是 String ,它也会进入 Default Case .. 为什么?不应该破吗?如果 TypeSwitch 中缺少某些东西,我该如何解决?
编辑
我不知道为什么每个人都认为我没有先调试它并继续进行投票。但我确实为此投入了大量时间。我检查了,我只是将 ProprtyType 作为 String 传递,它循环通过 CaseInfo 处理所有内容,然后转到 Do 并执行 Default Case .. 问题是我缺少什么?