-11

参考这个...

http://docs.oracle.com/javase/tutorial/reflect/index.html什么是反射,为什么它有用?

.Net 平台上有类似的东西吗?

4

1 回答 1

2

反射提供了封装程序集、模块和类型的对象(Type 类型)。您可以使用反射来动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性

我已经使用反射来动态加载程序集并在反射的帮助下显示其形式。

Step 1: Loading an assembly form the specified path.

string path = Directory.GetCurrentDirectory() + @"\dynamicdll.dll";
try
{
    asm = Assembly.LoadFrom(path);
}
catch (Exception)
{
}

Step 2: Getting all forms of an assembly dynamically & adding them to the list type.

List<Type> FormsToCall = new List<Type>();
Type[] types = asm.GetExportedTypes();
foreach (Type t in types)
{
    if (t.BaseType.Name == "Form")
        FormsToCall.Add(t);
}

Step 3:

int FormCnt = 0;
Type ToCall;
while (FormCnt < FormsToCall.Count)
{
     ToCall = FormsToCall[FormCnt];
     //Creates an instance of the specified type using the constructor that best matches the specified parameters.
     object ibaseObject = Activator.CreateInstance(ToCall);
     Form ToRun = ibaseObject as Form;
     try
     {
          dr = ToRun.ShowDialog();
          if (dr == DialogResult.Cancel)
          {
             cancelPressed = true;
             break;
          }
          else if (dr == DialogResult.Retry)
          {
             FormCnt--;
             continue;
          }
     }
     catch (Exception)
     {
     }
     FormCnt++;
}
于 2012-10-05T13:32:24.707 回答