首先想引用反射机制得引入一下命名空间
再写两个类,一个是Animal类,其中有一个Name属性,两个构造函数,一个Run方法。一个Cat类继承Animal类。
public class Animal
{
public string Name { get; set; }
public Animal(int a,double b,float c)
{
}
public Animal()
{
}
public void Run()
{
Console.WriteLine("animal is running. . . ");
}
}
public class Cat : Animal
{
}
}
运行以下代码,得到打印结果
Animal a = new Animal();
Type t = Type.GetType(" VR170602_Lesson25_Reflection.Animal");//得到其反射对象,t中存储的就是Animal类的信息
int length = t.GetConstructors().Length;//得到构造方法的数量
string str = t.GetConstructors()[1].Name; //得到构造器数组第一元素的名字,该属性永远为.ctor
Console.WriteLine(a.GetType());
Console.WriteLine(t.GetType());
Console.WriteLine(str);
Console.WriteLine(length);
构造器信息类
//构造器信息类
ConstructorInfo ci = t.GetConstructors()[0];//得到构造器数组第一元素的信息
Console.WriteLine(ci.GetParameters()[0].Name); //打印第一个构造器的参数名字
Console.WriteLine(ci.GetParameters()[0].ParameterType);//打印第一个构造器的参数类型
for (int i = 0; i < ci.GetParameters().Length; i++)
{
Console.WriteLine(ci.GetParameters()[i].ParameterType);
}//循环打印构造器的全部参数
object o = ci.Invoke(new object[] { 1, 2.5f, 1.3f });//调用构造器