VB 的 CreateObject 的 Microsoft 源代码。
<HostProtection(Resources:=HostProtectionResource.ExternalProcessMgmt)> _
<SecurityPermissionAttribute(SecurityAction.Demand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Public Function CreateObject(ByVal ProgId As String, Optional ByVal ServerName As String = "") As Object
'Creates local or remote COM2 objects. Should not be used to create COM+ objects.
'Applications that need to be STA should set STA either on their Sub Main via STAThreadAttribute
'or through Thread.CurrentThread.ApartmentState - the VB runtime will not change this.
'DO NOT SET THREAD STATE - Thread.CurrentThread.ApartmentState = ApartmentState.STA
Dim t As Type
If ProgId.Length = 0 Then
Throw VbMakeException(vbErrors.CantCreateObject)
End If
If ServerName Is Nothing OrElse ServerName.Length = 0 Then
ServerName = Nothing
Else
'Does the ServerName match the MachineName?
If String.Compare(Environment.MachineName, ServerName, StringComparison.OrdinalIgnoreCase) = 0 Then
ServerName = Nothing
End If
End If
Try
If ServerName Is Nothing Then
t = Type.GetTypeFromProgID(ProgId)
Else
t = Type.GetTypeFromProgID(ProgId, ServerName, True)
End If
Return System.Activator.CreateInstance(t)
Catch e As COMException
If e.ErrorCode = &H800706BA Then
'&H800706BA = The RPC Server is unavailable
Throw VbMakeException(vbErrors.ServerNotFound)
Else
Throw VbMakeException(vbErrors.CantCreateObject)
End If
Catch ex As StackOverflowException
Throw ex
Catch ex As OutOfMemoryException
Throw ex
Catch ex As System.Threading.ThreadAbortException
Throw ex
Catch e As Exception
Throw VbMakeException(vbErrors.CantCreateObject)
End Try
End Function