Reflection範例-2
第二個範例源自真實需求:
使用者目前僅提供兩、三種報表的需求,未來會再增加,但是希望增加報表需求時,不要異動到原有的程式。另外,在頁面上有個下拉選單,可以選擇報表(包含後來新增的),然後就可以顯示出來。
本文不是完整的解決方案,因為我只是寫個 sample 給 member 做參考。
我先開一個專案放 IReport 介面,定義好抓資料的方法和報表要顯示的名稱屬性:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Data;
6:
7: namespace RefelctionPractice_Interface
8: {
9: public interface IReport
10: {
11: DataTable GetData();
12: List<String> Keys();
13: String Title{get;}
14: }
15: }
然後報表專案實做這個介面:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using RefelctionPractice_Interface;
6: using System.Data;
7:
8: namespace ReflectionPractice_EntityClass
9: {
10: class UserReport : IReport
11: {
12: private String _title = "使用者報表";
13: #region IReport 成員
14:
15: System.Data.DataTable IReport.GetData()
16: {
17: DataTable dt = new DataTable();
18: dt.Columns.Add("UserID");
19: dt.Columns.Add("Name");
20: DataRow dr;
21: dr = dt.NewRow();
22: dr[0] = "Leo";
23: dr[1] = "里奧";
24: dt.Rows.Add(dr);
25: dr = dt.NewRow();
26: dr[0] = "Rose";
27: dr[1] = "螺絲";
28: dt.Rows.Add(dr);
29: return dt;
30: }
31:
32: List<string> IReport.Keys()
33: {
34: List<String> l = new List<string>();
35: l.Add("UserID");
36:
37: return l;
38: }
39: string IReport.Title
40: {
41: get { return _title; }
42: }
43:
44: #endregion
45: }
46: }
然後 View 這層就可以到指定的目錄中,載入所有實做 IReport 的報表專案,把 Title 顯示在下拉清單中,使用者選擇後就呼叫 GetData() 方法,把資料繫結到頁面上:
1: using System.Reflection;
2: using RefelctionPractice_Interface;
3: using System.Data;
4:
5: namespace ReflectionPractice_CS
6: {
7: class Program
8: {
9: static void Main(string[] args)
10: {
11: LoadUserReport();
12: Console.ReadLine();
13: }
14:
15: public static void LoadUserReport()
16: {
17: Assembly rpt = Assembly.LoadFile(@System.IO.Path.GetFullPath("./") + "ReflectionPractice_EntityClass.dll");
18: Type rptType = rpt.GetType("ReflectionPractice_EntityClass.UserReport");
19: Object obj;
20: IReport irpt;
21: try
22: {
23: obj = Activator.CreateInstance(rptType);
24: irpt = (IReport)obj;
25: }
26: catch (Exception ex)
27: {
28: Console.WriteLine(ex.Message);
29: return;
30: }
31: Console.WriteLine("Done!!!");
32: Console.WriteLine(irpt.Title);
33: DataTable dt = irpt.GetData();
34: foreach (DataRow dr in dt.Rows)
35: {
36: Console.WriteLine(dr[0].ToString() + " - " + dr[1].ToString());
37: }
38: }
39: }
40: }
很草稿的範例,不過至少該提到的重點都提了 :p
--------
沒什麼特別的~
不過是一些筆記而已