gpt4 book ai didi

c# - SqlConnection 类中的私有(private)构造函数采用参数 SqlConnection 类

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:10 25 4
gpt4 key购买 nike

我正在用 .Net Reflector 检查 SqlConnection .

我注意到有一个私有(private)构造函数,有趣的是它接受一个 SqlConnection 类作为参数。

我想知道的主要问题* 为什么 SqlConnection 采用 SqlConnection 类?* 私有(private)构造函数的用途是什么?

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;
}

最佳答案

你不需要为此使用 Reflector,源代码是 freely available online .

更重要的是,免费提供的在线版本的源代码立即向您展示了该构造函数的意义所在:它用于 SqlConnectionICloneable.Clone 实现>。新连接的属性应该与旧连接的属性相匹配,最简单的方法是复制属性。类设计者决定您不应尝试通过创建新的 SqlConnection 来克隆 SqlConnection,但显然,一些新的连接对象需要被创建,并且其他公共(public)构造函数与 Clone 的实现不匹配。因此,创建了一个新的构造函数,并限制了它的访问权限,以防止其他人(误)使用它。

关于c# - SqlConnection 类中的私有(private)构造函数采用参数 SqlConnection 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30529660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com