Home >Backend Development >C++ >How Can I Determine if a Generic Type Implements a Specific Generic Interface Using Only its Type Name?

How Can I Determine if a Generic Type Implements a Specific Generic Interface Using Only its Type Name?

Linda Hamilton
Linda HamiltonOriginal
2025-01-07 07:05:40750browse

How Can I Determine if a Generic Type Implements a Specific Generic Interface Using Only its Type Name?

Determining Interface Implementation of a Generic Type

Problem:

Consider these type definitions:

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

Objective:

How to determine if the type Foo implements the generic interface IBar when only the mangled type name is available.

Answer:

Utilizing the approach proposed by TcKs, we can employ the following LINQ query:

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

This query checks whether any of the implemented interfaces of the foo variable is a generic type and its generic type definition matches that of IBar. If such an interface exists, it indicates that Foo implements IBar.

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

Statement:
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