可能重复: 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<类型,INT> 会做的更好,的游客可能是矫枉过正但除此之外,它仍然是一个完全正常的解决方案。
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确定对象
发布评论