C# 反射泛型

 1 private static string GetValueString(string className, string filedName, int id, Assembly assembly) {
 2     Assembly ass = Assembly.GetExecutingAssembly();
 3     Type type = ass.GetType("Rws.BLL.BaseBLL.BaseOperationBLL`1");
 4     Type resultType = assembly.GetType("Rws.Model." + className);
 5     Type t = type.MakeGenericType(resultType);
 6     object obj = ass.CreateInstance(t.FullName);
 7     MethodInfo mi = t.GetMethod("SelectByID");
 8     object resultObject = mi.Invoke(obj, new object[] { id });
 9     var pInfo = resultType.GetProperty(filedName);
10     return pInfo.GetValue(resultObject, null).ToString();
11 }

注:[Rws.BLL.BaseBLL.BaseOperationBLL`1]的末尾为:`1,即重音符号(`)和数字1

 如果SelectByID有两个重载函数:

1 public T SelectByID(int autoID)
2 {
3         ......
4 }
5 public T SelectByID(string guid)
6 {
7         ......
8 }

现在反射调用参数为int类型的函数,将下面的代码替换上面的:

1 MethodInfo mi = t.GetMethod("SelectByID", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int) }, null);

 

posted @ 2013-11-30 08:44  zhuhc  阅读(955)  评论(0编辑  收藏  举报