反射重要属性方法
一、介绍
IsAssignableFrom()方法,子类赋给父类或者接口。验证是否接口子类(还可以加个判断不是抽象),父类用这个。
IsInstanceOfType,检查某个对象是否是某个类型,type.IsInstanceOfType(object)
IsAbstract,是否是抽象类,接口,抽象类,静态类
IsSubclassOf , 验证是否是父子类关键,和接口无关。type.IsSubclassOf (type)
二、用到的类
public class Person { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } public void SayHi() { Console.WriteLine("反射的方法调用此方法"); } public void SayHi(string name) { Console.WriteLine(name+"反射的方法调用此方法"); } } public class Student : Person, Iinterface { } public class Teacher : Person, Iinterface { } public interface Iinterface { } public abstract class MyClass1 { } public static class MyClass2 { }
三、测试
Type typePerson = typeof(Person); Type typeStudent = typeof(Student); Type typeTeacher = typeof(Teacher); //智能提示说明,指定的类型实例就是说参数的c ①IsAssignableFrom //表示要检查,能否将typeStudent的类型的对象赋值给typePerson的类型 bool b = typePerson.IsAssignableFrom(typeStudent); Console.WriteLine(b);//true bool b1 = typePerson.IsAssignableFrom(typeTeacher); Console.WriteLine(b1);//true bool b2 = typeStudent.IsAssignableFrom(typeTeacher); Console.WriteLine(b2);//false; ② IsInstanceOfType,检查某个对象是否是某个类型,是否是它父类 object objPerson = Activator.CreateInstance(typePerson); object objStudent = Activator.CreateInstance(typeStudent); object objTeacher = Activator.CreateInstance(typeTeacher); ////检查某个对象是否是某个类型的实例。 Console.WriteLine(typePerson.IsInstanceOfType(objPerson));//true Console.WriteLine(typePerson.IsInstanceOfType(objStudent));//true Console.WriteLine(typePerson.IsInstanceOfType(objTeacher));//true Console.WriteLine(typeTeacher.IsInstanceOfType(objStudent));//false Console.ReadKey(); ③bool IsSubclassOf(Type c):有2个Type的时候用这个,一个type,一个对象用上面那个;验证父子类,与接口无关 Console.WriteLine(typePerson.IsSubclassOf(typeStudent));//false Console.WriteLine(typePerson.IsSubclassOf(typeTeacher));//false Console.WriteLine(typeStudent.IsSubclassOf(typePerson));//true Console.WriteLine(typeTeacher.IsSubclassOf(typePerson));//true Type typeInterface = typeof(Iinterface); //验证是否是父子类关键,和接口无关。 Console.WriteLine(typeStudent.IsSubclassOf(typeInterface));//false Console.WriteLine(typeTeacher.IsSubclassOf(typeInterface));//false ④IsAbstract Type typeInterface = typeof(Iinterface);//接口 Type typeMyClass1 = typeof(MyClass1);//抽象类 Type typeMyClass2 = typeof(MyClass2); //静态类 Console.WriteLine(typePerson.IsAbstract);//false Console.WriteLine(typeStudent.IsAbstract);//false Console.WriteLine(typeTeacher.IsAbstract);//false Console.WriteLine(typeInterface.IsAbstract);//true Console.WriteLine(typeMyClass1.IsAbstract);//true Console.WriteLine(typeMyClass2.IsAbstract);//true Console.ReadKey();