TDBACore.vb的代码:

Imports System.ComponentModel
Imports System.Data

<EditorBrowsable(EditorBrowsableState.Never)> _
Public MustInherit Class TDBACore
    Private Shared FRefCount As Integer

    Friend Shared FIsBeginTran As Boolean = False

    Friend Shared FConnection As IDbConnection

    Friend Shared FTransaction As IDbTransaction

    Private disposedValue As Boolean

    Friend Shared iRecheckTimeout As Integer
    Friend Shared iConnectionTimeOut As Integer

    Friend MustOverride Function CreateConnection() As IDbConnection

    Public Sub New()
        Me.disposedValue = False
        If TDBACore.FRefCount = 0 Then
            TDBACore.FConnection = Me.CreateConnection()
        End If
        TDBACore.FRefCount += 1

    End Sub

   Friend Shared Sub OpenConnection(ByVal ConnectionString As String)
    If TDBACore.FConnection.State = ConnectionState.Closed Then
        TDBACore.FConnection.ConnectionString = ConnectionString
        TDBACore.FConnection.Open()
    End If
   End Sub
End Class
TDBOpener.vb的代码:

Public NotInheritable Class TDBOpener
    Inherits TDBACore
    Public Shared ReadOnly _TDBOpener As New TDBOpener()
    Friend Overrides Function CreateConnection() As IDbConnection
        Return New NpgsqlConnection()
    End Function

    Public Shared Sub SetTimeoutValue(ByVal param_iRecheckTimeout As Integer, ByVal param_iConnectionTimeOut As Integer)
        TDBACore.iConnectionTimeOut = param_iConnectionTimeOut
        TDBACore.iRecheckTimeout = param_iRecheckTimeout
    End Sub

    Public Shared Sub Open(ByVal ConnectionString As String)
        TDBACore.OpenConnection(ConnectionString)
    End Sub
 End Class

我测试通过Npgsql.dll 3.2.2.0连接到postgresql:

TDBOpener.Open("Server=192.168.1.10;Port=5434;UserId=postgres;Password=123456;Database=testdb;CommandTimeout=300;")

我使用Win 10,64bit,vs 2017 .Net Framework 4.6

如果我以[Debug]模式运行:它可以运行New()的功能TDBACore并连接OK。
但是,如果我以[Release]模式运行,它就不会转到New()TDBACore函数。
为什么?谢谢大家。(注:我尝试赢得7,没关系。)

最佳答案

相对于2017 .Net Framework 4.6,赢10、64位:
如果我以[Release]模式运行,则无法初始化Public Shared ReadOnly _TDBOpener As New TDBOpener()
我的解决方案编辑功能OpenTDBOpener:

Public Shared Sub Open(ByVal ConnectionString As String)
        If TDBACore.FConnection Is Nothing Then
            Dim obOpen = _TDBOpener
        End If
        TDBACore.OpenConnection(ConnectionString)
End Sub

10-04 16:34