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
Release: 2025-01-07 07:05:40
Original
723 people have browsed it

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> {}
Copy after login

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<>));
Copy after login

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!

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