在运行时获取对象类型

本文关键字:类型 取对象 获取 运行时 | 更新日期: 2023-09-27 18:05:46

我有下面的代码。我得到一个不知道类型的对象。我得检查一下三个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;
}

在运行时获取对象类型

我认为你需要使用 as 关键字。检查为(c# Reference)

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

(blah.Handle).AssociatedFeature  = requirementTemplate.GetAssociatedFeature();

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

var feature = requirementTemplate as IHasAssociatedFeature;
if(feature != null) {
    (blah.Handle).AssociatedFeature = feature.GetAssociatedFeature();
}

你也可以在左边做类似的事情,或者把它作为上下文传递:

var feature = requirementTemplate as IHasAssociatedFeature;
if(feature != null) {
     feature.SetAssociatedFeature(blah);
}

(如果有必要)

另一种常见的方法是在enum上执行switch:

switch(requirementTemplate.FeatureType) {
     case ...
}
这样做的一个好处是,它既可以是特定类型的,也可以是特定实例的。