2011-10-02 76 views
0

我想使用反射來執行下面的代碼行。在運行時投射物體

IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(Environment.SpecialFolder.Desktop.ToString()+"\\Max Y+Y.lnk"); 

我已經成功地獲得了表達的正確部分。

WshShell.CreateShortcut(....) 

通過使用

this.assembly = Assembly.LoadFrom(Environment.CurrentDirectory + "\\Interop.IWshRuntimeLibrary.dll"); 

      AppDomain.CurrentDomain.Load(assembly.GetName()); 

      this.WshShellClass = assembly.GetType("IWshRuntimeLibrary.WshShellClass"); 
object classInstance = Activator.CreateInstance(this.WshShellClass, null); 



      object[] parameters = new object[1]; 
      parameters[0] = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Max Y+Y.lnk"; 
      MethodInfo methodInfo = this.WshShellClass.GetMethod("CreateShortcut"); 

      object result = methodInfo.Invoke(classInstance, parameters); 

現在我想將它轉換類型的反對IWshRuntimeLibrary.IWshShortcut結果在上述情況下,並將其分配給。

IWshRuntimeLibrary.IWshShortcut desktopShortCut, 

這怎麼可能?

+0

到底什麼是做這個晚點?只需添加對c:\ windows \ system32 \ wshom.ocx的引用 –

+0

我正在開發安裝程序項目安裝屏蔽2011(限制版)。並將此代碼作爲exe自定義action.For由於某些原因,我無法添加參考。 –

回答

0

如果WshShellClass.CreateShortcut返回IWshRuntimeLibrary.IWshShortcut那麼你可以只說

IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut) result 

難道我失去了一些東西?

+0

但我動態加載包含類型IWshRuntimeLibrary.IshshShortcut的程序集。 –

+1

如果在編譯時不知道類型,那麼你不能投射到它:)你想隨後調用一個快捷方式的任何方法都必須通過反射。但是你應該調查爲什麼你不能添加參考 - 「出於某種原因」似乎不是一個很好的理由。 –