一、問題的出現測試
// 這個tableName是從報文裏讀取的,如今測試,我直接給個名字 string tableName = "BaoHuGuiHua"; // 反射獲取表名的Type Type type = Assembly.Load("Apt.MWSGR.Domain").GetType("Apt.MWSGR.Domain.Entities." + tableName); // 問題就在這,怎麼把BaoHuGuiHua這個實體傳到下面的泛型裏面去,就是大T那點我應該怎麼寫? var exportDataByTableNameQuery = new ExportDataByTableNameQuery<T>(); // 調用方法,獲取所有數據 var exportData = exportDataByTableNameQuery.GetAll();
public class ExportDataByTableNameQuery<T>:NHibernateQuery where T:class { public IEnumerable<T> GetAll() { return this.Session.Query<T>().ToList(); } }
二、方法一ui
經過Type類的Type.MakeGenericType方法獲取,詳細用法請參照MSDN,MSDN上的demo不是很明白,我下面的三行是CSDN上的大牛推薦的。this
// 這個tableName是從報文裏讀取的,如今測試,我直接給個名字 string tableName = "BaoHuGuiHua"; // 反射獲取表名的Type Type type = Assembly.Load("Apt.MWSGR.Domain").GetType("Apt.MWSGR.Domain.Entities." + tableName); type = typeof(ExportDataByTableNameQuery<>).MakeGenericType(type); object exportDataByTableNameQuery = Activator.CreateInstance(type); // 下面這句話是關鍵,太長了,分3行顯示 var exportData = type.GetMethod("GetAll", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new Type[0], null) .Invoke(exportDataByTableNameQuery, null);
三、方法二code
在此特別感謝個人同窗朱百青幫我寫的demo。get
static void Main(string[] args) { //System.Collections.Generic.List`1[ConsoleApplication1.Class1] //List<string> list = new List<string>(); //Console.WriteLine(list.ToString()); //Test<Class2> t = new Test<Class2>(); //Console.WriteLine(t.ToString()); Assembly ass = Assembly.LoadFile(@"C:\Users\cc-zbq\Documents\Visual Studio 2012\ Projects\項目\ConsoleApplication1\ClassLibrary1\bin\Debug\ClassLibrary1.dll"); object fanXing = ass.CreateInstance("ClassLibrary1.Test`1[ClassLibrary1.Class2]"); Type t = fanXing.GetType(); object lei = ass.CreateInstance("ClassLibrary1.Class2"); Type l = lei.GetType(); l.GetProperty("Name").SetValue(lei,"小強"); object result = t.GetMethod("Method1").Invoke(fanXing,new object[]{lei}); var r = result as IEnumerable; var r1 = r.GetEnumerator(); r1.Reset(); while (r1.MoveNext()) { Console.WriteLine(r1.Current.GetType().GetProperty("Name").GetValue(r1.Current) .ToString()); } // Console.WriteLine(result.ToString()); Console.ReadKey(); }
public class Test<T> where T: class,new() { public List<T> Method1(T t1) { var r=new List<T>(); r.Add(t1); return r; } }
public class Class2 { public string Name { get; set; } }
四、上述兩種方法的對比string
請你們留言寫下本身的想法,我模糊的想法是,一種是運行時的,一種是編譯時的。it
五、福利io