Define a derivation type from a generic type

I have the following utility program that determines if a type of a specific type occurs:

private static bool DerivesFrom(Type rType, Type rDerivedType)
{
    while ((rType != null) && ((rType != rDerivedType)))
        rType = rType.BaseType;
    return (rType == rDerivedType);
}

(actually I don't know if there is a more convenient way to check the output ...)

The problem is that I want to determine if a type arises from a generic type, but without specifying general arguments.

For example, I can write:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<ClassB>))

but i need the following

DerivesFrom(typeof(ClassA), typeof(MyGenericClass))

How can i achieve this?


Based on the example of Darin Miritrova, this is an example application:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ConsoleApplication1
{
    public class MyGenericClass<T> { }
    public class ClassB {}
    public class ClassA : MyGenericClass<ClassB> { }

    class Program
    {
        static void Main()
        {
            bool result = DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));
            Console.WriteLine(result); // prints **false**
        }

        private static bool DerivesFrom(Type rType, Type rDerivedType)
        {
            return rType.IsSubclassOf(rDerivedType);
        }
    }
}
+3
source share
1 answer

You can leave the general parameter open:

DerivesFrom(typeof(ClassA), typeof(MyGenericClass<>));

must work. Example:

public class ClassA { }
public class MyGenericClass<T>: ClassA { }

class Program
{
    static void Main()
    {
        var result = DerivesFrom(typeof(MyGenericClass<>), typeof(ClassA));
        Console.WriteLine(result); // prints True
    }

    private static bool DerivesFrom(Type rType, Type rDerivedType)
    {
        return rType.IsSubclassOf(rDerivedType);
    }
}

IsSubClassOf, DerivesFrom . IsAssignableFrom, .

+5

Source: https://habr.com/ru/post/1779824/


All Articles