C#Type类中的IsAssignableFrom、IsInstanceOfType、IsSubclassOf
先写两个有继承关系的类Person、Son和一个接口IProgram:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestType { interface IProgram { void Program (); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestType { public class Person : IProgram { public string Name; public int age; public void Say () { Console.WriteLine("Person Say"); } public void Program() { Console.WriteLine("Person Program"); } } }
一.测试IsAssignableFrom.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestType { class Program { static void Main(string[] args) { Type personTp = typeof(Person); Type sonTp = typeof(Son); Type programTp = typeof(IProgram); Console.WriteLine(personTp.IsAssignableFrom(sonTp)); Console.WriteLine(programTp.IsAssignableFrom (personTp)); Console.WriteLine(programTp.IsAssignableFrom(sonTp)); Console.WriteLine(programTp.IsAssignableFrom(programTp)); } } }
结果:
总结:
IsAssignableFrom判断参数类:
1.是否为当前类或接口.
2.是否继承当前类.
3.是否实现当前接口.
----------------------------------------------------------------------------------------------------------------
二.测试IsInstanceOfType.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestType { class Program { static void Main(string[] args) { Type personTp = typeof(Person); Type sonTp = typeof(Son); Type programTp = typeof(IProgram); Person person = new Person(); Son son = new Son(); Console.WriteLine(personTp.IsInstanceOfType(person)); Console.WriteLine(personTp.IsInstanceOfType(son)); Console.WriteLine(sonTp.IsInstanceOfType(person)); Console.WriteLine(sonTp.IsInstanceOfType(son)); Console.WriteLine(programTp.IsInstanceOfType(person)); Console.WriteLine(programTp.IsInstanceOfType(son)); } } }
结果:
总结:
IsInstanceOfType判断参数对象:
1.是否为当前类的实例.
2.是否实现了当前接口.
--------------------------------------------------------------------------------------------------------------------------------
三.测试IsSubclassOf.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestType { class Program { static void Main(string[] args) { Type personTp = typeof(Person); Type sonTp = typeof(Son); Type programTp = typeof(IProgram); Person person = new Person(); Son son = new Son(); Console.WriteLine(sonTp.IsSubclassOf(personTp)); Console.WriteLine(sonTp.IsSubclassOf(sonTp)); Console.WriteLine(sonTp.IsSubclassOf(programTp)); } } }
结果:
总结:
IsSubclassOf判断参数类型:
1.是否为当前类的父类.
2.不能判断接口.