日期:2014-05-18  浏览次数:20938 次

如何透过 Reflection 调用 dll 中的自订 class

我的 dll 档案
test.dll

  class Message_Show
  {
  public List<string> show()
  {
  List<string> msg = new List<string>();
  ...
  ...
  return (msg);
  }
  }

  class Main_Show
  {
  public string m1;
  public string m2;
  public string m3;

  public Main_Show show()
  {
  Main_Show ms = new Main_Show();
  ...
  ...
  return ms;
  }  
  }




主程序, 使用 Reflection 方式调用 test.dll

  若是调用 show()时, 当他为一般 List 型态就没问题
  Assembly dllFile = System.Reflection.Assembly.LoadFrom("test.dll");
  Type = dllFile.GetType("test.Message_Show");
  Object obj = dllFile.CreateInstance(type.FullName, true);
  MethodInfo mi = project.dll_method("show");
  List<string> msg = (List<string>)mi.Invoke(obj, null);

但是在掉用我自订类别的型态时, 该怎么调用呢?
  Assembly dllFile = System.Reflection.Assembly.LoadFrom("test.dll");
  Type = dllFile.GetType("test.Main_Show");
  Object obj = dllFile.CreateInstance(type.FullName, true);
  MethodInfo mi = project.dll_method("show");
  ??? = (???)mi.Invoke(obj, null);


------解决方案--------------------
反射的意义就在于事先不知道类型,你都能确定类型了就直接强制类型转换被。
------解决方案--------------------
然后再通过
Object.GetType

Type.GetProperty
Type.GetField
Type.GetMethod

取得属性,成员变量,方法等。
------解决方案--------------------
Class1 test = new Class1();
Type t = test.GetType();

MethodInfo[] test_method = t.GetMethods();
string[] s = { "B" };
MethodInfo method= t.GetMethod("");
object obj_name = Activator.CreateInstance(t, s);
method.Invoke(obj_name, null);

MethodInfo methodInfo = t.GetMethod("", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
methodInfo.Invoke(target, null); 

------解决方案--------------------
探讨
不太能了解4楼的程序, 有人能解释一下吗?

2楼, 能确定型态没错, 但型态是自订的而非一般型态,
所以无法强制转换, 强制转换只能像我第一个 List 的一般型态才能转