使用案例/开关和的GetType确定对象 [英] Using Case/Switch and GetType to determine the object

查看:167
本文介绍了使用案例/开关和的GetType确定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/298976/c-sharp-is-there-a-better-alternative-than-this-to-switch-on-type">C# - 是否有比这更好的选择的类型转换'

如果你想在对象类型开关,什么是做到这一点的最好方法是什么?

If you want to switch on a type of object, what is the best way to do this?

private int GetNodeType(NodeDTO node)
{
    switch (node.GetType())
    { 
        case typeof(CasusNodeDTO):
            return 1;
        case typeof(BucketNodeDTO):
            return 3;
        case typeof(BranchNodeDTO):
            return 0;
        case typeof(LeafNodeDTO):
            return 2;
        default:
            return -1;
    }
}

我知道这不工作的方式,但我不知道如何可以解决这个问题。 是一个的if / else 适当在这种情况下声明?

I know this doesn't work that way, but I was wondering how you could solve this. Is an if/else statement appropriate in this case?

或者你使用的开关,并添加的ToString()的类型?

Or do you use the switch and add .ToString() to the type?

推荐答案

如果我的真正的只好开关对象的类型,我D使用的ToString()。不过,我会避免它不惜一切代价:的IDictionary&LT;类型,INT&GT; 会做的更好,的游客可能是矫枉过正但除此之外,它仍然是一个完全正常的解决方案。

If I really had to switch on type of object, I'd use .ToString(). However, I would avoid it at all costs: IDictionary<Type, int> will do much better, visitor might be an overkill but otherwise it is still a perfectly fine solution.

这篇关于使用案例/开关和的GetType确定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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