Sometimes we need to determine whether a class implements an interface (Interface), such as when using the reflection mechanism (Reflection) to find a particular type.
In simple terms, you can use the Type.isassignablefrom method:
typeof (IFoo). IsAssignableFrom (bar. GetType ()); typeof (IFoo). IsAssignableFrom (typeof(Barclass));
As can be seen from the literal meaning, isassignablefrom indicates whether the Barclass type can be assigned to the IFoo interface, so it returns true if Barclass directly or indirectly implements the IFoo interface. There is one more method in type IsSubclassOf, which can only be used to determine the inheritance of a class, such as
typeof (Fooclass). IsSubclassOf (typeoftrue
Indicates that Fooclass is inherited from Barclass.
Of course isassignablefrom can also be used to judge inheritance relationships.
So, for the following code:
1 Interface /* * /}2class/** / }3 class/** /}
The return values for IsSubclassOf and IsAssignableFrom are:
typeof(A). IsAssignableFrom (typeof(I));//falsetypeof(A). IsSubclassOf (typeof(I));//false typeof(I). IsAssignableFrom (typeof(A));//truetypeof(I). IsAssignableFrom (typeof(B));//truetypeof(B). IsSubclassOf (typeof(I));//false typeof(A). IsAssignableFrom (typeof(A));//truetypeof(A). IsSubclassOf (typeof(A));//false typeof(A). IsAssignableFrom (typeof(B));//truetypeof(A). IsSubclassOf (typeof(B));//false typeof(B). IsAssignableFrom (typeof(A));//falsetypeof(B). IsSubclassOf (typeof(A));//true
". Net" in C # to determine whether a class implements an interface