This article is a mirror article of machine translation, please click here to jump to the original article.

View: 63994|Reply: 1

[Source] C# inherits the determination of IsAssignableFrom, IsSubclassOf

[Copy link]
Posted on 11/18/2019 11:45:09 AM | | |
Sometimes we need to determine whether a class implements an interface, such as when using a reflection mechanism to find a specific type.

In simple terms, you can use the Type.IsAssignableFrom method:

IsAssignableFrom indicates whether the BarClass type can be assigned to the IFoo interface, so the condition for it to return true is that BarClass directly or indirectly implements the IFoo interface. There is also a method in the Type type, IsSubclassOf, which isOnlyUsed to judge inheritance relationships of classes, such as

Indicates that FooClass is inherited from BarClass.

Of course, IsAssignableFrom can also be used to determine inheritance.

So, for the following code:

interface I { /* ... */ }
class A : I { /* ... */ }
class B : A { /* ... */ }
The return values for IsSubclassOf and IsAssignableFrom are:

typeof(A).isAssignableFrom(typeof(I)); // false
typeof(A).isSubClassOf(typeof(I)); // false
  
typeof(I).isAssignableFrom(typeof(A)); // true
typeof(I).isAssignableFrom(typeof(B)); // true
typeof(B).isSubClassOf(typeof(I)); // false
  
typeof(A).isAssignableFrom(typeof(A)); // true
typeof(A).isSubClassof(typeof(A)); // false
  
typeof(A).isAssignableFrom(typeof(B)); // true
typeof(A).isSubClassof(typeof(B)); // false
  
typeof(B).isAssignableFrom(typeof(A)); // false
typeof(B).isSubClassof(typeof(A)); // true






Previous:.NET Core Timestamp Conversion (10-bit)
Next:EF Core pit: DbContextPool causes database connection pool connection exhaustion
 Landlord| Posted on 3/19/2021 1:39:47 PM |
Gets an object that inherits a generic base class

Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com