". Net" in C # to determine whether a class implements an interface

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.