C#判断类是否继承某个类或接口

69 阅读1分钟

C#判断类是否继承某个类或接口 C#判断某个类是否派生某个类或是否实现了某个接口 - dreamw - 博客园 (cnblogs.com)

这个跟自己预想的还是不太一样啊!

public interface IInterface{}
public class Parent { }
public class Children :Parent, IInterface { }

判断是否继承类:Type.IsSubclassOf()

typeof(Children).IsSubclassOf(typeof(Parent))

public static void Main()
{
  Console.WriteLine("Children is a subclass of IInterface:   {0}",
                    typeof(Children).IsSubclassOf(typeof(IInterface))); //False
  Console.WriteLine("Children subclass of Class1: {0}",
                    typeof(Children).IsSubclassOf(typeof(Parent))); //True
}

learn.microsoft.com/zh-cn/dotne…

判断是否继承自接口: Type.IsAssignableFrom()

typeof(Parent).IsSubclassOf(typeof(Children))

 public static void Main()
{
    Console.WriteLine("IInterface is assignable from Children: {0}",
                    typeof(IInterface).IsAssignableFrom(typeof(Children))); //True
    Console.WriteLine("Parent is assignable from Children: {0}",
                    typeof(Parent).IsAssignableFrom(typeof(Children))); //True
}