简体   繁体   English

Basetype的BaseType

[英]BaseType of a Basetype

this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy. 这是我在这里的第一个问题,所以我希望我能够很好地表达出来,并希望它不会太令人头疼。

I have the following class SubSim which extends Sim , which is extending MainSim . 我有以下类SubSim扩展了Sim ,它扩展了MainSim In a completely separate class (and library as well) I need to check if an object being passed through is a type of MainSim . 在一个完全独立的类(和库)中,我需要检查传递的对象是否是一种MainSim So the following is done to check; 所以要做以下检查;

Type t = GetType(sim);
//in this case, sim = SubSim
if (t != null)
{
  return t.BaseType == typeof(MainSim);
}

Obviously t.BaseType is going to return Sim since Type.BaseType gets the type from which the current Type directly inherits. 显然t.BaseType将返回Sim,因为Type.BaseType获取当前Type直接继承的类型。

Short of having to do t.BaseType.BaseType to get MainSub , is there any other way to get the proper type using .NET libraries? 除了必须执行t.BaseType.BaseType以获取MainSub之外 ,还有其他方法可以使用.NET库获取正确的类型吗? Or are there overrides that can be redefined to return the main class? 或者是否有可以重新定义以返回主类的覆盖?

Thank you in advance 先感谢您

There are 4 related standard ways: 有4种相关的标准方式:

sim is MainSim;
(sim as MainSim) != null;
sim.GetType().IsSubclassOf(typeof(MainSim));
typeof(MainSim).IsAssignableFrom(sim.GetType());

You can also create a recursive method: 您还可以创建递归方法:

bool IsMainSimType(Type t)
 { if (t == typeof(MainSim)) return true;   
   if (t == typeof(object) ) return false;
   return IsMainSimType(t.BaseType);
 }
if (sim is MainSim)

is all you need. 是你所需要的全部。 "is" looks up the inheritance tree. “是”查找继承树。

使用is关键字

return t is MainSim;

The 'is' option didn't work for me. '是'选项对我不起作用。 It gave me the warning; 它给了我警告; "The given expression is never of the provided ('MainSim') type", I do believe however, the warning had more to do with the framework we have in place. “给定的表达式永远不会是提供的('MainSim')类型”,但我确实相信,警告更多地与我们现有的框架有关。 My solution ended up being: 我的解决方案最终成为:

return t.BaseType == typeof(MainSim) || t.BaseType.IsSubclassof(typeof(MainSim));

Not as clean as I'd hoped, or as straightforward as your answers seemed. 不像我希望的那样干净,或者像你的答案那样直截了当。 Regardless, thank you everyone for your answers. 无论如何,谢谢大家的答案。 The simplicity of them makes me realize I have much to learn. 它们的简单性让我意识到我需要学习很多东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM