Using Case/Switch and GetType to determine the object(使用 Case/Switch 和 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?
推荐答案
如果我真的必须switch
对象的类型,我会使用.ToString()
.但是,我会不惜一切代价避免它:IDictionary<Type, int>
会做得更好,visitor 可能有点矫枉过正,但除此之外它仍然是一个完美的解决方案.
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.
这篇关于使用 Case/Switch 和 GetType 确定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Case/Switch 和 GetType 确定对象


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01