How to determine if a type is in the inheritance hierarchy

I need to determine if an object has a specific type in the inheritance hierarchy, however I cannot find a good way to do this.

A very simple example of my classes:

Public Class Domain End Class Public Class DerivedOne Inherits Domain End Class Public Class DerivedTwo Inherits DerivedOne End Class Public Class DerivedThree Inherits Domain End Class 

The following works, however, in my opinion, it is not very elegant. In addition, the more inheritance levels that are created, the more checks must be performed, and it would be easy to forget that this piece of code needs to be updated.

 If GetType(T) Is GetType(Domain) OrElse _ GetType(T).BaseType Is GetType(Domain) OrElse _ GetType(T).BaseType.BaseType Is GetType(Domain) Then End If 

Is there a way to get "Domain Type Anywhere in the T Inheritance Hierarchy"?

(Answers are welcome in C # or VB.NET)


UPDATE

One bit of vital information that I missed because of my own idiocy!

T is an object of type (from a generic class type)

+6
source share
4 answers

You can use the Type.IsAssignableFrom method.

In VB:

 If GetType(Domain).IsAssignableFrom(GetType(DerivedThree)) Then 

In C #:

 if (typeof(Domain).IsAssignableFrom(typeof(DerivedThree))) 
+17
source

VB:

 If TypeOf x Is Domain Then 

WITH#:

 if(x is Domain) 

To make it shared:

WITH#

 bool IsInHierarchy<T>(object x) { return x.GetType() is typeof(T); } 

This is all you need to check if x is a type that comes from a domain

Just read this code as: โ€œif x can be thought of as a domain objectโ€

By definition, all type objects that are derived from a domain can be tested as a Domain object.

+5
source

In C # (VB should also have this), you can use a shorthand expression to test and use a variable and exclude a part of the cast:

 var val = x as Domain; 

And then use val like this:

 if(val != null) { // use val } 
0
source

How about being an operator ?

 if(obj is Domain) { // } 
-3
source

Source: https://habr.com/ru/post/946270/


All Articles