C#开启式 [英] C# switch on type

查看:78
本文介绍了C#开启式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/298976/c-sharp-is-there-a-better-alternative-than-this-to-switch-on-type\">C# - 是否有比这更好的替代品上式开关'

C#不支持的对象的类型的切换。什么是这个模拟的最佳方式:

C# doesn't support switching on the type of an object. What is the best pattern of simulating this:

switch (typeof(MyObj))
    case Type1:
    case Type2:
    case Type3:

谢谢!

推荐答案

我通常使用的种类和代表的字典。

I usually use a dictionary of types and delegates.

var @switch = new Dictionary<Type, Action> {
    { typeof(Type1), () => ... },
    { typeof(Type2), () => ... },
    { typeof(Type3), () => ... },
};

@switch[typeof(MyType)]();

这是一个少flexable因为你无法通过的情况下回落,继续等,但我很少这样做呢。

It's a little less flexable as you can't fall through cases, continue etc. But I rarely do so anyway.

这篇关于C#开启式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆