對於Eric Lippert或熟悉JScript引擎實現的Microsoft人員來說,這確實是一個問題。在JScript中:我可以枚舉通過新的ActiveXObject()創建的對象上的方法嗎?
我可以這樣做:
var obj = new ActiveXObject("My.ProgId");
var methods = GetMethodsViaMagic(obj);
?
(假設COM類型支持的IDispatch)
如果是這樣,什麼是GetMethodsViaMagic()
樣子?
編輯 - 當然,我想的第一件事就是for...in
循環,但這並不對ActiveX對象定義的方法和屬性的作用。至少,不適用於我在.NET中定義並通過ComVisible
公開的對象。
在C#中,我可以這樣定義的IDispatch:
[Guid("00020400-0000-0000-c000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDispatch
{
int GetTypeInfoCount();
System.Runtime.InteropServices.ComTypes.ITypeInfo
GetTypeInfo([MarshalAs(UnmanagedType.U4)] int iTInfo,
[MarshalAs(UnmanagedType.U4)] int lcid);
[PreserveSig]
int GetIDsOfNames(ref Guid riid,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] rgsNames,
int cNames,
int lcid,
[MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);
[PreserveSig]
int Invoke(int dispIdMember,
ref Guid riid,
[MarshalAs(UnmanagedType.U4)] int lcid,
[MarshalAs(UnmanagedType.U4)] int dwFlags,
ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams,
[Out, MarshalAs(UnmanagedType.LPArray)] object[] pVarResult,
ref System.Runtime.InteropServices.ComTypes.EXCEPINFO pExcepInfo,
[Out, MarshalAs(UnmanagedType.LPArray)] IntPtr[] pArgErr);
}
然後,我可以做這樣的事情:
var idispatch = (IDispatch) comObject ;
System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo =
idispatch.GetTypeInfo(0, 0);
System.Runtime.InteropServices.ComTypes.FUNCDESC funcDesc;
string strName, strDocString, strHelpFile;
int dwHelpContext;
typeInfo.GetFuncDesc(i, out pFuncDesc);// i = 1, 2, 3...
funcDesc = (System.Runtime.InteropServices.ComTypes.FUNCDESC)
Marshal.PtrToStructure(pFuncDesc,
typeof(System.Runtime.InteropServices.ComTypes.FUNCDESC));
...並得到函數(方法)的名字,和參數的數量等。
我可以在JScript中爲ActiveX(COM IDispatch)對象做類似的事嗎?
感謝您的貢獻,Lippert先生。擁有你描述的功能將會很方便。無法想象現在添加該功能會破壞很多程序。我知道Win8會獲得更多的Javascript愛;看起來非常有趣。 – Cheeso