Home > Backend Development > C++ > How Can I Reliably Identify Derived Classes from a Generic Class in C#?

How Can I Reliably Identify Derived Classes from a Generic Class in C#?

DDD
Release: 2025-01-24 18:57:16
Original
365 people have browsed it

How Can I Reliably Identify Derived Classes from a Generic Class in C#?

The derivative class of generating generic categories in C#

Inheritance in object -oriented inheritance allows the function of extending its parent class. When using generic classes, determining whether a class is derived from a specific generic class may help. However, check the Issubclassof attribute may not work as expected.

In order to solve this problem, we can use the ISSUBCLASSOFRAWGENERC method, which compares the type definition of the parent class with the types provided.

The following code fragment demonstrates how to use this method:

By comparative generic type definition rather than a complete limited type name, the IssubclassOfrawgneric method can accurately determine whether a class is assigned to self -generation.
<code class="language-csharp">static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
    while (toCheck != null && toCheck != typeof(object)) {
        var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
        if (generic == cur) {
            return true;
        }
        toCheck = toCheck.BaseType;
    }
    return false;
}</code>
Copy after login

The above is the detailed content of How Can I Reliably Identify Derived Classes from a Generic Class 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template