Home > Backend Development > C++ > How Can I Determine if a Type Implements a Specific Generic Interface in C#?

How Can I Determine if a Type Implements a Specific Generic Interface in C#?

Barbara Streisand
Release: 2025-01-07 07:19:41
Original
812 people have browsed it

How Can I Determine if a Type Implements a Specific Generic Interface in C#?

Determining if a Type Implements a Specific Generic Interface Type

Suppose you have the following type definitions:

public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
Copy after login

Given only the mangled type, how can you determine if the type Foo implements the generic interface IBar?

Solution with LINQ Query

As suggested by TcKs, you can utilize the following LINQ query:

bool isBar = foo.GetType().GetInterfaces().Any(x =>
  x.IsGenericType &amp;&amp;
  x.GetGenericTypeDefinition() == typeof(IBar<>));
Copy after login

This query checks if any of the implemented interfaces of foo is a generic type that matches the IBar definition. The Any() method returns true if at least one interface meets that criteria.

The above is the detailed content of How Can I Determine if a Type Implements a Specific Generic Interface in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template