首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在运行时获取对象类型

在运行时获取对象类型
EN

Stack Overflow用户
提问于 2011-08-17 13:00:16
回答 2查看 2.5K关注 0票数 4

下面有密码。我得到了一个我不知道类型的物体。我必须检查三个条件,如果条件检查它的类型,然后作出正确的铸造。

是否有任何方法在运行时获取对象类型并进行强制转换,而不检查任何if条件?

我拥有的对象是requirementTemplate,我必须用许多类型检查它,以得到它的类型,然后进行转换。

代码语言:javascript
复制
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;
}
EN

回答 2

Stack Overflow用户

发布于 2011-08-17 13:02:26

我认为您需要使用as关键字。检查为(C#参考)

票数 3
EN

Stack Overflow用户

发布于 2011-08-17 13:05:17

这里最合适的答案是要么实现公共接口,要么重写来自公共基类的虚拟方法,并使用多态性在运行时提供实现(来自各种实现类)。然后,您的方法变成:

代码语言:javascript
复制
(blah.Handle).AssociatedFeature  = requirementTemplate.GetAssociatedFeature();

如果列表不是排他性的(即存在其他实现),那么:

代码语言:javascript
复制
var feature = requirementTemplate as IHasAssociatedFeature;
if(feature != null) {
    (blah.Handle).AssociatedFeature = feature.GetAssociatedFeature();
}

您也可以在左手边做类似的事情,也可以将其作为上下文传递:

代码语言:javascript
复制
var feature = requirementTemplate as IHasAssociatedFeature;
if(feature != null) {
     feature.SetAssociatedFeature(blah);
}

(如有需要)

另一种常见的方法是在此处对枚举进行switch

代码语言:javascript
复制
switch(requirementTemplate.FeatureType) {
     case ...
}

这方面的一个好处是,它可以是特定类型的,也可以是特定于实例的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7093262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档