2011-10-02 53 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

如果在编译时不知道类型,那么你不能投射到它:)你想随后调用一个快捷方式的任何方法都必须通过反射。但是你应该调查为什么你不能添加参考 - “出于某种原因”似乎不是一个很好的理由。 –