简体   繁体   中英

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 . In a completely separate class (and library as well) I need to check if an object being passed through is a type of 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.

Short of having to do t.BaseType.BaseType to get MainSub , is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class?

Thank you in advance

There are 4 related standard ways:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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