26 .net com reflection interop com-interop
我在Visual Studio中引用了一个COM库,因此它为我自动创建了相应的Interop程序集.我想GetType()
对这些com对象做一个,但它们总是返回System.__ComObject
.查询它们的接口有效:
bool isOfType = someComeObject is ISomeComObject; //this works
Run Code Online (Sandbox Code Playgroud)
但我真正想要的是返回com对象的实际类型:
Type type = someComeObject.GetType(); //returns System.__ComObject :-(
Run Code Online (Sandbox Code Playgroud)
有谁知道怎么做我想做的事情?
Dar*_*rov 54
添加引用Microsoft.VisualBasic.dll
然后:
Microsoft.VisualBasic.Information.TypeName(someCOMObject)
Run Code Online (Sandbox Code Playgroud)
MSDN 在这里参考.
Dir*_*mar 10
达林接受的答案需要依赖Microsoft.VisualBasic.dll
.如果你不想拥有它,你可以使用这个简单的助手类:
public static class TypeInformation
{
public static string GetTypeName(object comObject)
{
var dispatch = comObject as IDispatch;
if (dispatch == null)
{
return null;
}
var pTypeInfo = dispatch.GetTypeInfo(0, 1033);
string pBstrName;
string pBstrDocString;
int pdwHelpContext;
string pBstrHelpFile;
pTypeInfo.GetDocumentation(
-1,
out pBstrName,
out pBstrDocString,
out pdwHelpContext,
out pBstrHelpFile);
string str = pBstrName;
if (str[0] == 95)
{
// remove leading '_'
str = str.Substring(1);
}
return str;
}
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14640 次 |
最近记录: |