反射_元数据<14/9/2017>
1.程序是用来处理数据的,文本和特性都是数据,而程序本身(类的定义和BLC中的类)这些也是数据.
2.有关程序及类型的数据被称为元数据(metadata),它们保存在程序的程序集中.
3.程序在运行时,可以查看其他程序集或其本身的元数据.一个运行的程序查看本身的元数据或者其他程序集的元数据的行为叫做反射.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;//反射需要引用命名空间
using System.Text;
using System.Threading.Tasks;
namespace 反射
{
class Program
{
static void Main(string[] args)
{
//每一个类对应一个type对象,这个type对象存储了这个类有哪些方法/哪些数据/哪些成员
MyClass my = new MyClass();//类中的数据是存储在对象中的,type对象只存储类的成员
Type type = my.GetType();//通过对象获取这个对象所属类的Type对象
Console.WriteLine(type.Name);//获取类的名字
Console.WriteLine(type.Namespace);//获取所在的命名空间
Console.WriteLine(type.Assembly);//获取其程序集的信息
FieldInfo[] array = type.GetFields();//只能够获取共有字段
foreach (FieldInfo info in array)
{
Console.Write(info.Name+" ");
}
PropertyInfo[] array2 = type.GetProperties();
foreach (PropertyInfo info in array2)
{
Console.Write(info.Name+" ");
}
MethodInfo[] array3 = type.GetMethods();
foreach(MethodInfo info in array3)
{
Console.Write(info.Name+" ");
}
//通过type对象可以获取它对应的类的所有成员(public),无法获取私有的
Console.ReadKey();
}
}
}
创建一个类来读
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 反射 { class MyClass { private int id; private int age; public int number; public string Name { get; set; } public string Name1 { get; set; } public string Name2 { get; set; } public void Test1() { } public void Test2() { } } }