C# 运行时强制转换对象
我想使用反射执行以下代码行C# 运行时强制转换对象,c#,reflection,C#,Reflection,我想使用反射执行以下代码行 IWshRuntimeLibrary.IWshShortcut desktopShortCut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(Environment.SpecialFolder.Desktop.ToString()+"\\Max Y+Y.lnk"); 我已经成功地得到了正确的表达部分 WshShell.CreateShortcut(....) 利用 this.assembly
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
我遗漏了什么吗?但我正在动态加载包含类型IWshRuntimeLibrary.IWshShortcut的程序集。如果在编译时不知道该类型,则无法将其强制转换为:)任何希望随后调用该快捷方式的方法都必须通过反射。但是你应该调查为什么你不能添加引用--“出于某种原因”似乎不是一个好的理由。这么晚做到底有什么意义?只需添加对c:\windows\system32\wshom.ocxI的引用,我正在使用installer project install shield 2011(限量版)。并在自定义操作中将此代码作为exe运行。由于某些原因,我无法添加引用。