我正在编写一些测试代码来模拟调用我的后期绑定 COM 对象的 c# 实现的非托管代码。我有一个声明为 IDispatch 类型的接口,如下所示。
[Guid("2D570F11-4BD8-40e7-BF14-38772063AAF0")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface TestInterface
{
int Test();
}
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TestImpl : TestInterface
{
...
}
当我使用下面的代码调用 IDispatch 的GetIDsOfNames
函数时
..
//code provided by Hans Passant
Object so = Activator.CreateInstance(Type.GetTypeFromProgID("ProgID.Test"));
string[] rgsNames = new string[1];
int[] rgDispId = new int[1];
rgsNames[0] = "Test";
//the next line throws an exception
IDispatch disp = (IDispatch)so;
其中 IDispatch 定义为:
//code provided by Hans Passant
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")]
private interface IDispatch {
int GetTypeInfoCount();
[return: MarshalAs(UnmanagedType.Interface)]
ITypeInfo GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid);
void GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames, [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);
}
抛出 InvalidCastException。是否可以将 ac# 接口转换为 IDispatch?