c#反射

 反射的定义:审查元数据并收集关於它的类型信息的能力,元数据(编辑后的基本数据单元)就是一大堆表,编译器会创建一个类定义表,一个字段定义表,一个方法定义表等,System.Reflection命名空间包含的几个类,允许你反射(解析)这些元数据的代码。
        简单来理解:就是编译器在编译反射相关的代码时,会将所有的类、方法、属性等分别创建一个表,而每个表的元素都对应着一部分元数据中的代码。当我们利用类名称字符串去创建这个类中,程序会在保存类中表中找到我们提供的这个类名称,然后再找到对应的构造函数,并执行。

反射中的类型

MemberInfo-反射类的成员 
ConstructorInfo-反射类的构造函数 
FieldInfo-反射类的字段 
MethodInfo-反射类的构造函数的方法 
PropertyInfo-反射类的构造函数的属性 
EventInfo-反射类的构造函数的事件

代码

using ReflectionInjection.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


namespace Reflection
{
class Program
{
static void Main1(string[] args)
{

Assembly assembly = Assembly.Load("TestClass"); //TestClass程序集dll文件
Type[] types = assembly.GetTypes();
Type type = types[0];
string className = "Reflection." + "Student";
string className2 = "Reflection." + "Person"; //Person代表的是这个程序集里面要查找的类;Reflection 代表的是程序集
// string className3 = "ReflectionInjection.Helper." + "MacButtonn";
Student stu= Assembly.Load("Reflection").CreateInstance(className) as Student;
Person person = Assembly.Load("Reflection").CreateInstance(className2) as Person;
// MacButtonn macButton = Assembly.Load("ReflectionInjection").CreateInstance(className3) as MacButtonn;

Console.ReadKey();
}

static void Main(string[] args)
{

Assembly assembly = Assembly.Load("TestClass");
Type[] types = assembly.GetTypes(); //获取数据集中所有的数据类型(即我们在dll中定义的类)
Type type = types[0];
object obj1 = Activator.CreateInstance(type);
FieldInfo[] listFinfo = type.GetFields(); //字段
foreach (FieldInfo finfo in listFinfo)
{
var name = finfo.GetValue(obj1); //字段的值
Console.WriteLine("字段的名字 " + finfo.Name+"字段的值"+name);
}
PropertyInfo[] listPropertyInfo = type.GetProperties(); //属性
foreach (PropertyInfo propertyInfo in listPropertyInfo) {
var name = propertyInfo.GetValue(obj1, null); //属性的值
Console.WriteLine("属性的名字 " + propertyInfo.Name);
}

MethodInfo[] minfos = type.GetMethods(); //方法
foreach (MethodInfo me in minfos)
{
if (me.Name == "Run")
{
object o=me.Invoke(obj1, null); //调用方法
string ss = "nihao";

}
}


Console.WriteLine(type.FullName);
Console.ReadKey();
}

}

public class Student
{
public string _name = "dsc";
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}

public string Run()
{
return "Hello World";
}
}
}

 

namespace TestClass
{
class Person
{

public string _name = "dsc";
public string Name { get; set; }

public int Age { get; set; }

public string Run()
{
return "你好,我是测试类";
}
}
}

posted @ 2018-02-09 10:13  哈根达斯  阅读(176)  评论(1编辑  收藏  举报