一:反射的定義
審查元數據並收集關於它的類型信息的能力。元數據(編譯以后的最基本數據單元)就是一大堆的表,當編譯程序集或者模塊時,編譯器會創建一個類定義表,一個字段定義表,和一個方法定義表等。
System.reflection命名空間包含的幾個類,允許你反射(解析)這些元數據表的代碼
System.Reflection.Assembly
System.Reflection.MemberInfo
System.Reflection.EventInfo
System.Reflection.FieldInfo
System.Reflection.MethodBase
System.Reflection.ConstructorInfo
System.Reflection.MethodInfo
System.Reflection.PropertyInfo
System.Type
層次模型:

二:獲取類型信息:
1 class MyClass 2 { 3 public string m; 4 public void test() { } 5 public int MyProperty { get; set; } 6 } 7 8 //獲取類型信息 9 protected void Button1_Click(object sender, EventArgs e) 10 { 11 Type type = typeof(MyClass); 12 Response.Write("類型名:" + type.Name); 13 Response.Write("<br/>"); 14 Response.Write("類全名:" + type.FullName); 15 Response.Write("<br/>"); 16 Response.Write("命名空間名:" + type.Namespace); 17 Response.Write("<br/>"); 18 Response.Write("程序集名:" + type.Assembly); 19 Response.Write("<br/>"); 20 Response.Write("模塊名:" + type.Module); 21 Response.Write("<br/>"); 22 Response.Write("基類名:" + type.BaseType); 23 Response.Write("<br/>"); 24 Response.Write("是否類:" + type.IsClass); 25 Response.Write("<br/>"); 26 Response.Write("類的公共成員:"); 27 Response.Write("<br/>"); 28 MemberInfo[] memberInfos = type.GetMembers();//得到所有公共成員 29 foreach (var item in memberInfos) 30 { 31 Response.Write(string.Format("{0}:{1}", item.MemberType, item)); 32 Response.Write("<br/>"); 33 } 34 }
三:獲取程序集信息
protected void Button2_Click(object sender, EventArgs e)
{
//獲取當前執行代碼的程序集
Assembly assem = Assembly.GetExecutingAssembly();
Response.Write("程序集全名:"+assem.FullName);
Response.Write("<br/>");
Response.Write("程序集的版本:"+assem.GetName().Version);
Response.Write("<br/>");
Response.Write("程序集初始位置:"+assem.CodeBase);
Response.Write("<br/>");
Response.Write("程序集位置:"+assem.Location);
Response.Write("<br/>");
Response.Write("程序集入口:"+assem.EntryPoint);
Response.Write("<br/>");
Type[] types = assem.GetTypes();
Response.Write("程序集下包含的類型:");
foreach (var item in types)
{
Response.Write("<br/>");
Response.Write("類:"+item.Name);
}
}
四:反射調用方法
protected void Page_Load(object sender, EventArgs e)
{
System.Reflection.Assembly ass = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+"bin\\WebApplication1.dll"); //加載DLL
System.Type t = ass.GetType("WebApplication1.MainPage");//獲得類型
string name=typeof(MainPage).AssemblyQualifiedName;
System.Type t1 = Type.GetType(name);
System.Type t2 = typeof(MainPage);
object o = System.Activator.CreateInstance(t);//創建實例
System.Reflection.MethodInfo mi = t.GetMethod("RunJs1");//獲得方法
mi.Invoke(o, new object[] { this.Page, "alert('測試反射機制')" });//調用方法
System.Reflection.MethodInfo mi1 = t.GetMethod("RunJs");
mi1.Invoke(t, new object[] { this.Page, "alert('測試反射機制1')" });//調用方法
}
五:反射調用用戶/自定義控件
protected override void OnInit(EventArgs e)
{
//生成控件
CreateControl();
base.OnInit(e);
}
private void CreateControl()
{
Table tb = new Table();
TableRow dr = new TableRow();
TableCell cell = new TableCell();
Control c = LoadControl("WebUserControl1.ascx");
cell.Controls.Add(c);
dr.Cells.Add(cell);
tb.Rows.Add(dr);
this.PlaceHolder1.Controls.Add(tb);
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (TableRow tr in PlaceHolder1.Controls[0].Controls)
{
foreach (TableCell tc in tr.Controls)
{
foreach (Control ctl in tc.Controls)
{
if (ctl is UserControl)
{
Type type = ctl.GetType();
System.Reflection.MethodInfo methodInfo = type.GetMethod("GetResult");
string selectedValue = string.Concat(methodInfo.Invoke(ctl, new object[] { }));
Response.Write(selectedValue);
break;
}
}
}
}
}
六:反射實現工廠模式
public partial class 反射 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string typeName = typeof(TestClass).AssemblyQualifiedName;
ITestInterface iface = RawGenericFactory.Create<ITestInterface>(typeName);
string result = iface.doSomething();
Response.Write(result);
}
}
public static class RawGenericFactory
{
public static T Create<T>(string typeName)
{
//Activator.CreateInstance 反射 根據程序集創建借口或者類
//Type.GetType() 根據名稱獲得程序集信息
//typeof(ConcertProduct).AssemblyQualifiedName
//_iproduct.GetType().AssemblyQualifiedName
return (T)Activator.CreateInstance(Type.GetType(typeName));
}
}
public interface ITestInterface
{
string doSomething();
}
public class TestClass : ITestInterface
{
public int Id { get; set; }
public override string ToString()
{
return Id.ToString();
}
public string doSomething()
{
return "ok";
}
}
七:自定義ORM框架
[Orm.Table("TestORM")]
public class TestORM
{
[Orm.Colum("Id",DbType.Int32)]
public int Id { get; set; }
[Orm.Colum("UserName", DbType.String)]
public string UserName { get; set; }
[Orm.Colum("Password", DbType.String)]
public string Password { get; set; }
[Orm.Colum("CreatedTime", DbType.DateTime)]
public DateTime CreatedTime { get; set; }
}
protected void Button3_Click(object sender, EventArgs e)
{
TestORM t = new TestORM()
{
Id=1,
UserName="binfire",
Password="xxx",
CreatedTime=DateTime.Now
};
Orm.OrmHelp h=new Orm.OrmHelp();
h.Insert(t);
}
namespace Orm
{
[AttributeUsageAttribute(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class TableAttribute : Attribute
{
//保存表名的字段
private string _tableName;
public TableAttribute()
{
}
public TableAttribute(string tableName)
{
this._tableName = tableName;
}
///
/// 映射的表名(表的全名:模式名.表名)
///
public string TableName
{
set
{
this._tableName = value;
}
get
{
return this._tableName;
}
}
}
[AttributeUsageAttribute(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class ColumAttribute : Attribute
{
private string _columName;
private DbType _dbType;
public ColumAttribute()
{
}
public ColumAttribute(string columName)
: this()
{
this._columName = columName;
}
public ColumAttribute(string columName, DbType dbType)
: this(columName)
{
this._dbType = dbType;
}
//列名
public virtual string ColumName
{
set
{
this._columName = value;
}
get
{
return this._columName;
}
}
//描述一些特殊的數據庫類型
public DbType DbType
{
get { return _dbType; }
set { _dbType = value; }
}
}
public class OrmHelp
{
public void Insert(object table)
{
Type type = table.GetType();
//定義一個字典來存放表中字段和值的對應序列
Dictionary<string,string> columValue = new Dictionary<string,string>();
StringBuilder SqlStr = new StringBuilder();
SqlStr.Append("insert into ");
//得到表名子
TableAttribute temp = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false).First();
SqlStr.Append(temp.TableName);
SqlStr.Append("(");
PropertyInfo[] Propertys = type.GetProperties();
foreach (var item in Propertys)
{
object[] attributes = item.GetCustomAttributes(false);
foreach (var item1 in attributes)
{
//獲得相應屬性的值
string value = table.GetType().InvokeMember(item.Name, System.Reflection.BindingFlags.GetProperty, null, table, null).ToString();
ColumAttribute colum = item1 as ColumAttribute;
if (colum != null)
{
columValue.Add(colum.ColumName, value);
}
}
}
//拼插入操作字符串
foreach (var item in columValue)
{
SqlStr.Append(item.Key);
SqlStr.Append(",");
}
SqlStr.Remove(SqlStr.Length - 1, 1);
SqlStr.Append(") values('");
foreach (var item in columValue)
{
SqlStr.Append(item.Value);
SqlStr.Append("','");
}
SqlStr.Remove(SqlStr.Length - 2, 2);
SqlStr.Append(")");
HttpContext.Current.Response.Write(SqlStr.ToString());
}
}
}
