C# 在运行时获取对象类型
我有下面的代码。我得到了一个我不知道其类型的对象。我得检查一下 如果有三个条件检查其类型,则进行正确的转换 有没有办法在运行时获取对象类型并进行转换, 不检查任何if条件 我拥有的对象是C# 在运行时获取对象类型,c#,dynamic-typing,C#,Dynamic Typing,我有下面的代码。我得到了一个我不知道其类型的对象。我得检查一下 如果有三个条件检查其类型,则进行正确的转换 有没有办法在运行时获取对象类型并进行转换, 不检查任何if条件 我拥有的对象是requirementTemplate,我必须用许多类型检查它,以获得它的类型,然后进行转换 if (requirementTemplate.GetType() == typeof(SRS_Requirement)) { ((SRS_Requirement)((TreeNodeInfo)ParentTre
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;
}
我认为您需要使用
作为
关键字。
Check as这里最合适的答案是实现公共接口,或者从公共基类重写虚拟方法,并在运行时使用多态性提供实现(从各种实现类)。然后,您的方法变成:
(blah.Handle).AssociatedFeature = requirementTemplate.GetAssociatedFeature();
如果列表不是排他性的(即存在其他实现),则:
您也可以在左手边做类似的事情,或者将其作为上下文传递:
var feature = requirementTemplate as IHasAssociatedFeature;
if(feature != null) {
feature.SetAssociatedFeature(blah);
}
(如有需要)
另一种常见的方法是在枚举上切换:
switch(requirementTemplate.FeatureType) {
case ...
}
它的一个优点是,它可以是特定于类型的,也可以是特定于实例的。为什么要用3个不同的C版本来标记它?它是哪一个?如果您提取
((TreeNodeInfo)ParentTreeNode.Tag)。将
处理到一个单独的变量中,您的代码将更加清晰。你还应该考虑使用<代码>是,而不是调用<代码> GETType()/<代码>。这在技术上是正确的答案,尽管它没有解决代码墙所隐含的糟糕的设计。我不知道这会对他的设计有什么帮助。为了访问AssociatedFeature属性,他仍然需要硬编码用于强制转换的类型。因此,仍然需要所有的if语句,这是他想要减少的。。。另一个答案(接口)更合适,我想说这是“有没有办法在运行时获取对象类型并进行转换,而不检查任何if条件?”:D
switch(requirementTemplate.FeatureType) {
case ...
}