How to check if a type arises from an abstract base type?

Hi, I have an abstract generic type BList<TElement> where TElement : Career . A career is also abstract.

Given type T, how can I check if this is a type of BList? And how can I apply the base class? I tried the (BList<Career>)object , but the compiler was upset. Apparently, I can't write BList<Career> because Career is abstract.

+4
source share
2 answers

There's a bit of ambiguity with your question, so I will try to answer some of the things that I think you can ask for ...

If you want to check if the instance is T BList, you can simply use is :

 if (someInstance is BList<Career>) { ... } 

If you want to find out if the parameter is of type type BList<Career> , you can use typeof :

 if (typeof(T) == typeof(BList<Career>) { ... } 

But if you just want to see if it is a BList<> , you can use reflection:

 var t = typeof(T); // or someInstance.GetType() if you have an instance if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BList<>)) { ... } 

Now, how much have you applied BList<TElement> to BList<Career> ? You cannot be safe.

This is not because Career is abstract; it is because BList<Career> does not inherit from BList<TElement> , although Career inherits from TElement .

Consider this:

 public class Animal { } public class Dog : Animal { } public class Cat : Animal { } 

Given this, ask yoruself why this does not work:

 List<Animal> animals = new List<Cat>(); 

See the problem? If we allow you to apply a List<Cat> to a List<Animal> , then suddenly the Add() method will support Animal instead of Cat , which means you could do this:

 animals.Add(new Dog()); 

Obviously, we cannot add Dog to the List<Cat> . This is why you cannot use List<Cat> as List<Animal> , although Cat inherits from Animal .

A similar case is here.

+8
source
 var item = theObject as BList<Career>; 

If it is null , then this is not the type.

+1
source

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


All Articles