• notice
  • Congratulations on the launch of the Sought Tech site

Determine whether a class inherits from a generic base class in c#

In c#, sometimes we write code like this:

public class a<T>
{ //The implementation of the concrete class
}
public class b : a<string>{}

If the type of b inheriting a is uncertain, at this time we cannot directly judge whether b inherits from a through baseType.

If we write the following code:

typeof(b).baseType == typeof(a)

The return value is false.

Because typeof(b).baseTypethe returned type is a`1[System.String], and the typeof(a<>)returned type is a`1[T]. Obviously the two types are not equal. So the above return flaseis normal.


So how to solve this problem?

The easiest way is definitely typeof(b).baseType == typeof(a<string>)to return true like this.

But since we used T, there is a high probability that we do not know the incoming type, so this method does not work.

The other method is a little more troublesome.

First, we convert the generic type to a generic prototype, and then we can compare the generic prototype.

C# provides a method for obtaining generic prototypes GetGenericTypeDefinition(), which MSDN explains as follows:

Returns a Type object representing a generic type definition that can be used to construct the current generic type.

So we can use it typeof(b).baseType.GetGenericTypeDefinition()directly a<>.

It should be noted here that an GetGenericTypeDefinition()exception will be thrown when b is not a generic type, so we should judge whether b is a generic class before using it.

This method is also provided in c#, IsGenericTypeand MSDN explains it as follows:

Gets a value indicating whether the current type is a generic type.

So the way we judge whether a class inherits from a generic base class is like this:

if (typeof(b).baseType.IsGenericType && typeof(b).baseType.GetGenericTypeDefinition() == typeof(a)){
// here is the logic that b inherits from a<T>
}


Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

lipitor 10mg us & lt;a href="https://lipiws.top/"& gt;atorvastatin 10mg usa& lt;/a& gt; order atorvastatin 80mg without preion

Tveqfa

2024-03-09

Leave a Reply

+