Check if a class is derived from a generic class

前端 未结 16 1360
太阳男子
太阳男子 2020-11-22 09:57

I have a generic class in my project with derived classes.

public class GenericClass : GenericInterface
{
}

public class Test : GenericCla         


        
16条回答
  •  有刺的猬
    2020-11-22 10:26

    Simple solution: just create and add a second, non-generic interface to the generic class:

    public interface IGenericClass
    {
    }
    
    public class GenericClass : GenericInterface, IGenericClass
    {
    }
    

    Then just check for that in any way you like using is, as, IsAssignableFrom, etc.

    if (thing is IGenericClass)
    {
        // Do work
    {
    

    Obviously only possible if you have the ability to edit the generic class (which the OP seems to have), but it's a bit more elegant and readable than using a cryptic extension method.

提交回复
热议问题