开发者

Get object type in runtime

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).AssociatedFea开发者_JS百科ture = ((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 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:

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

If the list is not exclusive (i.e. other implementations exist), then:

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

you can do similar things on the left hand side too, or pass that in as context:

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

(if necessary)


Another not-uncommon approach is to switch on an enum here:

switch(requirementTemplate.FeatureType) {
     case ...
}

one nice thing about this is that it can be either type-specific or instance-specific.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜