如何将类型_ComObject转换为本机类型,如Long或其他(获得强制转换错误)?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将类型_ComObject转换为本机类型,如Long或其他(获得强制转换错误)?相关的知识,希望对你有一定的参考价值。
我试图通过调用从Active Directory获取LastLogonTimestamp
Principal.ExtensionGet("lastLogonTimestamp")
VB.NET代码:
<DirectoryProperty("lastLogonTimestamp")>
Public Property LastLogonTimestamp() As Date? ' no matter what this type is, I cannot cast the Object coming in
Get
Dim valueArray = ExtensionGet("lastLogonTimestamp")
If valueArray Is Nothing OrElse valueArray.Length = 0 Then Return Nothing
Return DateTime.FromFileTimeUtc(valueArray(0))
End Get
Set(value As Date?)
ExtensionSet("lastLogonTimestamp", value)
End Set
End Property
这将返回Object
(即Object()
)或null
的数组。麻烦的是它抱怨我的演员对Long
(或其他类型我尝试过:ULong
,Date
和String
)。它总是告诉我这样的事情:
从类型'_ComObject'到类型'Long'的转换无效。
在a new question,我开始走另一条路(从DateTime到64位)
通过下面的HansPassant评论使用link中提供的C#代码,我使用以下VB代码解决了这个问题:
<DirectoryProperty("lastLogonTimestamp")>
Public Property LastLogonTimestamp() As Date?
Get
'Dim valueArray = GetProperty("whenChanged")
Dim valueArray = ExtensionGet("lastLogonTimestamp") 'ExtensionGet("LastLogon")
If valueArray Is Nothing OrElse valueArray.Length = 0 Then Return Nothing
Dim lastLogonDate = valueArray(0)
Dim lastLogonDateType = lastLogonDate.GetType()
Dim highPart = CType(lastLogonDateType.InvokeMember("HighPart", Reflection.BindingFlags.GetProperty, Nothing, lastLogonDate, Nothing), Int32)
Dim lowPart = CType(lastLogonDateType.InvokeMember("LowPart", Reflection.BindingFlags.GetProperty Or Reflection.BindingFlags.Public, Nothing, lastLogonDate, Nothing), Int32)
Dim longDate = CLng(highPart) << 32 Or (CLng(lowPart) And &HFFFFFFFFL)
Dim result = IIf(longDate > 0, CType(DateTime.FromFileTime(longDate), DateTime?), Nothing)
Return result
'Return DateTime.FromFileTimeUtc(valueArray(0))
End Get
Set(value As Date?)
ExtensionSet("lastLogonTimestamp", value)
End Set
End Property
而C#版本(剪辑自source):
[DirectoryProperty("RealLastLogon")]
public DateTime? RealLastLogon
{
get
{
if (ExtensionGet("LastLogon").Length > 0)
{
var lastLogonDate = ExtensionGet("LastLogon")[0];
var lastLogonDateType = lastLogonDate.GetType();
var highPart = (Int32)lastLogonDateType.InvokeMember("HighPart", BindingFlags.GetProperty, null, lastLogonDate, null);
var lowPart = (Int32)lastLogonDateType.InvokeMember("LowPart", BindingFlags.GetProperty | BindingFlags.Public, null, lastLogonDate, null);
var longDate = ((Int64)highPart << 32 | (UInt32)lowPart);
return longDate > 0 ? (DateTime?) DateTime.FromFileTime(longDate) : null;
}
return null;
}
}
以上是关于如何将类型_ComObject转换为本机类型,如Long或其他(获得强制转换错误)?的主要内容,如果未能解决你的问题,请参考以下文章
无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型
VS2015:无法将“System.__ComObject”类型的 COM 对象转换为接口类型“IFabricTestManagementClient4”[重复]
无法将类型为“System .__ ComObject”的COM对象强制转换为类类型AgentInfo
SQL Server Management Studio 无法将类型为“System.__ComObject
求sql中解决连接错误 无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类 型
SQL SERVER2005遇到的问题:无法将类型为“System.__ComObject”的 COM 对象强制转换为接口类型