在运行时强制转换对象

本文关键字:转换 对象 运行时 | 更新日期: 2023-09-27 18:10:18

我想使用反射执行以下代码行。

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,

这怎么可能?

在运行时强制转换对象

如果WshShellClass.CreateShortcut返回一个IWshRuntimeLibrary.IWshShortcut那么你可以直接写

IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut) result

我错过了什么吗?