Determine whether a class implements an interface in C #

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:

12 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

1 typeof (Fooclass). IsSubclassOf (typeof (Barclass)) = = True

Indicates that Fooclass is inherited from Barclass.

Of course isassignablefrom can also be used to judge inheritance relationships.

So, for the following code:

123 Interface I {/* ... */}class A:I {/* * ... */}class b:a {/* ... */}

The return values for IsSubclassOf and IsAssignableFrom are:

123456789101112131415 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

Determine whether a class implements an interface in C #

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.