反射主要使用的命名空间:
System.Reflection
System.Type
System.Reflection.Assembly
本质:元数据
反射的本质其实是使用元数据;元数据其实就是程序编译出来的特定数据结构的表;当编译程序集或者模块时,编译器会创建一个类定义表,一个字段定义表,和一个方法定义表等;用过c++的可能会类比一下头文件;
反射的作用就是解析使用这些元数据;上面的几个命名空间就是实现这些解析与使用。
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Practice.NET.Reflact { public class Product { public string Name { get; set; } public decimal Price { get; set; } public Product() { } public Product(string name, decimal price) { this.Name = name; this.Price = price; } public void PrintName() { Console.WriteLine(this.Name); } void PrintPrice() { Console.WriteLine(this.Price.ToString()); } public string GetName(string name) { this.Name = name; return this.Name; } public void GetName() { PrintName(); } public void ShowPrice(ref decimal price) { this.Price = price; } } }