我檢查SqlConnection
並使用.Net Reflector。SqlConnection類中的私有構造函數參數SqlConnection類
我注意到有一個私人構造函數,有趣的是它需要作爲參數SqlConnection
類。
我不知道的主要問題 *爲什麼SqlConnection
需要SqlConnection
類? *它是什麼使用私人構造函數?
private SqlConnection(SqlConnection connection)
{
this._reconnectLock = new object();
this._originalConnectionId = Guid.Empty;
this.ObjectID = Interlocked.Increment(ref _objectTypeCount);
GC.SuppressFinalize(this);
this.CopyFrom(connection);
this._connectionString = connection._connectionString;
if (connection._credential != null)
{
SecureString password = connection._credential.Password.Copy();
password.MakeReadOnly();
this._credential = new SqlCredential(connection._credential.UserId, password);
}
}
public SqlConnection()
{
this._reconnectLock = new object();
this._originalConnectionId = Guid.Empty;
this.ObjectID = Interlocked.Increment(ref _objectTypeCount);
GC.SuppressFinalize(this);
this._innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
更新: 隨着Hvd's answer引導我找到了一個用法:
object ICloneable.Clone()
{
SqlConnection sqlConnection = new SqlConnection(this);
Bid.Trace("<sc.SqlConnection.Clone|API> %d#, clone=%d#\n", this.ObjectID, sqlConnection.ObjectID);
return (object) sqlConnection;
}
至於你的第二個問題,私人構造函數常用於[singleton pattern](http://csharpindepth.com/articles/general/singleton.aspx)。 – Eminem
看起來像*複製構造函數*在C++ –
我猜這是它如何處理混合模式身份驗證(SQL與Windows)。我再次猜測。 –