运行时获取对象类型
我有下面的代码。我得到一个我不知道类型的对象。我必须检查一下 三个 if 条件来检查其类型,然后进行正确的转换。
有什么方法可以在运行时获取对象类型并进行强制转换, 不检查任何 if 条件?
我拥有的对象是 requirementTemplate
,我必须使用多种类型检查它以获取其类型,然后进行强制转换。
if (requirementTemplate.GetType() == typeof(SRS_Requirement))
{
((SRS_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SRS_Requirement)requirementTemplate).AssociatedFeature;
}
else if (requirementTemplate.GetType() == typeof(CRF_Requirement))
{
((CRF_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = customAttr.saveAttributesCustomList(AttributesCustomListCloned);
}
else if (requirementTemplate.GetType() == typeof(SAT_TestCase))
{
((SAT_TestCase)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SAT_TestCase)requirementTemplate).AssociatedFeature;
}
I have the code below. I get an object whose type I don't know. I have to check
three if conditions to check its type, then make the right cast.
Is there any way to get the object type at runtime, and make the cast,
without checking any if condition?
The object I have is requirementTemplate
, and I have to check it with many types to get its type then make the cast.
if (requirementTemplate.GetType() == typeof(SRS_Requirement))
{
((SRS_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SRS_Requirement)requirementTemplate).AssociatedFeature;
}
else if (requirementTemplate.GetType() == typeof(CRF_Requirement))
{
((CRF_Requirement)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = customAttr.saveAttributesCustomList(AttributesCustomListCloned);
}
else if (requirementTemplate.GetType() == typeof(SAT_TestCase))
{
((SAT_TestCase)((TreeNodeInfo)ParentTreeNode.Tag).Handle).AssociatedFeature = ((SAT_TestCase)requirementTemplate).AssociatedFeature;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要使用
as
关键字。检查为(C# 参考)
I think you need to use
as
keyword.Check as (C# Reference)
这里最合适的答案是实现一个公共接口,或者从公共基类重写虚拟方法,并使用多态性在运行时提供实现(来自各种实现类)。那么你的方法就变成:
如果列表不是排他的(即存在其他实现),那么:
你也可以在左侧做类似的事情,或者将其作为上下文传递:(
如果需要)
另一种常见的方法是在这里切换枚举:
一个好处是它可以是特定于类型的,也可以是特定于实例的。
the most appropriate answer here would be to either implement a common interface, or override a virtual method from a common base-class, and use polymorphism to provide the implementation (from the various implementing classes) at runtime. Then your method becomes:
If the list is not exclusive (i.e. other implementations exist), then:
you can do similar things on the left hand side too, or pass that in as context:
(if necessary)
Another not-uncommon approach is to
switch
on an enum here:one nice thing about this is that it can be either type-specific or instance-specific.