使用案例/开关和的GetType确定对象

编程入门 行业动态 更新时间:2024-10-28 17:24:50
本文介绍了使用案例/开关和的GetType确定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:   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确定对象

本文发布于:2023-11-25 07:41:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628901.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   案例   GetType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!