2012-10-05 67 views

回答

2

反射提供封裝程序集,模塊和類型的對象(類型爲Type)。您可以使用反射來動態創建類型的實例,將類型綁定到現有對象,或從現有對象獲取類型並調用其方法或訪問其字段和屬性

我已經使用反射動態加載在Reflection的幫助下組裝並顯示其形式。

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++; 
} 
相關問題