最近在使用Java的数据库连接池,那么C#针对Sql Server有没有数据库连接池呢?

首先我们需要一个数据库连接字符串,例如:"Data Source=server;Initial Catalog=test;User ID=sa;Password=123456;"

其实这个连接字符串的配置对应着一个类:System.Data.SqlClient.SqlConnectionStringBuilder,在这个类中详细的规定了联机的具体参数,

下面看看这个类的具体代码:

[TypeConverter(typeof(SqlConnectionStringBuilderConverter)), DefaultProperty("DataSource")]
    public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder
    {
        // Fields
        private ApplicationIntent _applicationIntent;
        private string _applicationName;
        private bool _asynchronousProcessing;
        private string _attachDBFilename;
        private bool _connectionReset;
        private int _connectTimeout;
        private bool _contextConnection;
        private string _currentLanguage;
        private string _dataSource;
        private bool _encrypt;
        private bool _enlist;
        private string _failoverPartner;
        private string _initialCatalog;
        private bool _integratedSecurity;
        private static readonly Dictionary<string, Keywords> _keywords;
        private int _loadBalanceTimeout;
        private int _maxPoolSize;
        private int _minPoolSize;
        private bool _multipleActiveResultSets;
        private bool _multiSubnetFailover;
        private string _networkLibrary;
        private int _packetSize;
        private string _password;
        private bool _persistSecurityInfo;
        private bool _pooling;
        private bool _replication;
        private string _transactionBinding;
        private bool _trustServerCertificate;
        private string _typeSystemVersion;
        private string _userID;
        private bool _userInstance;
        private static readonly string[] _validKeywords;
        private string _workstationID;
        internal const int KeywordsCount = 0x1f;

        // Methods
        static SqlConnectionStringBuilder()
        {
            string[] strArray = new string[0x1f];
            strArray[0x1d] = "ApplicationIntent";
            strArray[0x17] = "Application Name";
            strArray[12] = "Asynchronous Processing";
            strArray[2] = "AttachDbFilename";
            strArray[13] = "Connection Reset";
            strArray[0x1b] = "Context Connection";
            strArray[0x10] = "Connect Timeout";
            strArray[0x18] = "Current Language";
            strArray[0] = "Data Source";
            strArray[0x11] = "Encrypt";
            strArray[8] = "Enlist";
            strArray[1] = "Failover Partner";
            strArray[3] = "Initial Catalog";
            strArray[4] = "Integrated Security";
            strArray[0x13] = "Load Balance Timeout";
            strArray[11] = "Max Pool Size";
            strArray[10] = "Min Pool Size";
            strArray[14] = "MultipleActiveResultSets";
            strArray[30] = "MultiSubnetFailover";
            strArray[20] = "Network Library";
            strArray[0x15] = "Packet Size";
            strArray[7] = "Password";
            strArray[5] = "Persist Security Info";
            strArray[9] = "Pooling";
            strArray[15] = "Replication";
            strArray[0x1c] = "Transaction Binding";
            strArray[0x12] = "TrustServerCertificate";
            strArray[0x16] = "Type System Version";
            strArray[6] = "User ID";
            strArray[0x1a] = "User Instance";
            strArray[0x19] = "Workstation ID";
            _validKeywords = strArray;
            Dictionary<string, Keywords> dictionary = new Dictionary<string, Keywords>(0x34, StringComparer.OrdinalIgnoreCase);
            dictionary.Add("ApplicationIntent", Keywords.ApplicationIntent);
            dictionary.Add("Application Name", Keywords.ApplicationName);
            dictionary.Add("Asynchronous Processing", Keywords.AsynchronousProcessing);
            dictionary.Add("AttachDbFilename", Keywords.AttachDBFilename);
            dictionary.Add("Connect Timeout", Keywords.ConnectTimeout);
            dictionary.Add("Connection Reset", Keywords.ConnectionReset);
            dictionary.Add("Context Connection", Keywords.ContextConnection);
            dictionary.Add("Current Language", Keywords.CurrentLanguage);
            dictionary.Add("Data Source", Keywords.DataSource);
            dictionary.Add("Encrypt", Keywords.Encrypt);
            dictionary.Add("Enlist", Keywords.Enlist);
            dictionary.Add("Failover Partner", Keywords.FailoverPartner);
            dictionary.Add("Initial Catalog", Keywords.InitialCatalog);
            dictionary.Add("Integrated Security", Keywords.IntegratedSecurity);
            dictionary.Add("Load Balance Timeout", Keywords.LoadBalanceTimeout);
            dictionary.Add("MultipleActiveResultSets", Keywords.MultipleActiveResultSets);
            dictionary.Add("Max Pool Size", Keywords.MaxPoolSize);
            dictionary.Add("Min Pool Size", Keywords.MinPoolSize);
            dictionary.Add("MultiSubnetFailover", Keywords.MultiSubnetFailover);
            dictionary.Add("Network Library", Keywords.NetworkLibrary);
            dictionary.Add("Packet Size", Keywords.PacketSize);
            dictionary.Add("Password", Keywords.Password);
            dictionary.Add("Persist Security Info", Keywords.PersistSecurityInfo);
            dictionary.Add("Pooling", Keywords.Pooling);
            dictionary.Add("Replication", Keywords.Replication);
            dictionary.Add("Transaction Binding", Keywords.TransactionBinding);
            dictionary.Add("TrustServerCertificate", Keywords.TrustServerCertificate);
            dictionary.Add("Type System Version", Keywords.TypeSystemVersion);
            dictionary.Add("User ID", Keywords.UserID);
            dictionary.Add("User Instance", Keywords.UserInstance);
            dictionary.Add("Workstation ID", Keywords.WorkstationID);
            dictionary.Add("app", Keywords.ApplicationName);
            dictionary.Add("async", Keywords.AsynchronousProcessing);
            dictionary.Add("extended properties", Keywords.AttachDBFilename);
            dictionary.Add("initial file name", Keywords.AttachDBFilename);
            dictionary.Add("connection timeout", Keywords.ConnectTimeout);
            dictionary.Add("timeout", Keywords.ConnectTimeout);
            dictionary.Add("language", Keywords.CurrentLanguage);
            dictionary.Add("addr", Keywords.DataSource);
            dictionary.Add("address", Keywords.DataSource);
            dictionary.Add("network address", Keywords.DataSource);
            dictionary.Add("server", Keywords.DataSource);
            dictionary.Add("database", Keywords.InitialCatalog);
            dictionary.Add("trusted_connection", Keywords.IntegratedSecurity);
            dictionary.Add("connection lifetime", Keywords.LoadBalanceTimeout);
            dictionary.Add("net", Keywords.NetworkLibrary);
            dictionary.Add("network", Keywords.NetworkLibrary);
            dictionary.Add("pwd", Keywords.Password);
            dictionary.Add("persistsecurityinfo", Keywords.PersistSecurityInfo);
            dictionary.Add("uid", Keywords.UserID);
            dictionary.Add("user", Keywords.UserID);
            dictionary.Add("wsid", Keywords.WorkstationID);
            _keywords = dictionary;
        }

        public SqlConnectionStringBuilder()
            : this(null)
        {
        }

        public SqlConnectionStringBuilder(string connectionString)
        {
            this._applicationName = ".Net SqlClient Data Provider";
            this._attachDBFilename = "";
            this._currentLanguage = "";
            this._dataSource = "";
            this._failoverPartner = "";
            this._initialCatalog = "";
            this._networkLibrary = "";
            this._password = "";
            this._transactionBinding = "Implicit Unbind";
            this._typeSystemVersion = "Latest";
            this._userID = "";
            this._workstationID = "";
            this._connectTimeout = 15;
            this._maxPoolSize = 100;
            this._packetSize = 0x1f40;
            this._connectionReset = true;
            this._enlist = true;
            this._pooling = true;
            if (!ADP.IsEmpty(connectionString))
            {
                base.ConnectionString = connectionString;
            }
        }

        public override void Clear()
        {
            base.Clear();
            for (int i = 0; i < _validKeywords.Length; i++)
            {
                this.Reset((Keywords)i);
            }
        }

        public override bool ContainsKey(string keyword)
        {
            ADP.CheckArgumentNull(keyword, "keyword");
            return _keywords.ContainsKey(keyword);
        }

        private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value)
        {
            return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value);
        }

        private static bool ConvertToBoolean(object value)
        {
            return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
        }

        private static int ConvertToInt32(object value)
        {
            return DbConnectionStringBuilderUtil.ConvertToInt32(value);
        }

        private static bool ConvertToIntegratedSecurity(object value)
        {
            return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value);
        }

        private static string ConvertToString(object value)
        {
            return DbConnectionStringBuilderUtil.ConvertToString(value);
        }

        private object GetAt(Keywords index)
        {
            switch (index)
            {
                case Keywords.DataSource:
                    return this.DataSource;

                case Keywords.FailoverPartner:
                    return this.FailoverPartner;

                case Keywords.AttachDBFilename:
                    return this.AttachDBFilename;

                case Keywords.InitialCatalog:
                    return this.InitialCatalog;

                case Keywords.IntegratedSecurity:
                    return this.IntegratedSecurity;

                case Keywords.PersistSecurityInfo:
                    return this.PersistSecurityInfo;

                case Keywords.UserID:
                    return this.UserID;

                case Keywords.Password:
                    return this.Password;

                case Keywords.Enlist:
                    return this.Enlist;

                case Keywords.Pooling:
                    return this.Pooling;

                case Keywords.MinPoolSize:
                    return this.MinPoolSize;

                case Keywords.MaxPoolSize:
                    return this.MaxPoolSize;

                case Keywords.AsynchronousProcessing:
                    return this.AsynchronousProcessing;

                case Keywords.ConnectionReset:
                    return this.ConnectionReset;

                case Keywords.MultipleActiveResultSets:
                    return this.MultipleActiveResultSets;

                case Keywords.Replication:
                    return this.Replication;

                case Keywords.ConnectTimeout:
                    return this.ConnectTimeout;

                case Keywords.Encrypt:
                    return this.Encrypt;

                case Keywords.TrustServerCertificate:
                    return this.TrustServerCertificate;

                case Keywords.LoadBalanceTimeout:
                    return this.LoadBalanceTimeout;

                case Keywords.NetworkLibrary:
                    return this.NetworkLibrary;

                case Keywords.PacketSize:
                    return this.PacketSize;

                case Keywords.TypeSystemVersion:
                    return this.TypeSystemVersion;

                case Keywords.ApplicationName:
                    return this.ApplicationName;

                case Keywords.CurrentLanguage:
                    return this.CurrentLanguage;

                case Keywords.WorkstationID:
                    return this.WorkstationID;

                case Keywords.UserInstance:
                    return this.UserInstance;

                case Keywords.ContextConnection:
                    return this.ContextConnection;

                case Keywords.TransactionBinding:
                    return this.TransactionBinding;

                case Keywords.ApplicationIntent:
                    return this.ApplicationIntent;

                case Keywords.MultiSubnetFailover:
                    return this.MultiSubnetFailover;
            }
            throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
        }

        private Keywords GetIndex(string keyword)
        {
            Keywords keywords;
            ADP.CheckArgumentNull(keyword, "keyword");
            if (!_keywords.TryGetValue(keyword, out keywords))
            {
                throw ADP.KeywordNotSupported(keyword);
            }
            return keywords;
        }

        protected override void GetProperties(Hashtable propertyDescriptors)
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(this, true))
            {
                bool flag2 = false;
                bool isReadOnly = false;
                string displayName = descriptor.DisplayName;
                if ("Integrated Security" == displayName)
                {
                    flag2 = true;
                    isReadOnly = descriptor.IsReadOnly;
                }
                else
                {
                    if (!("Password" == displayName) && !("User ID" == displayName))
                    {
                        continue;
                    }
                    isReadOnly = this.IntegratedSecurity;
                }
                Attribute[] attributesFromCollection = base.GetAttributesFromCollection(descriptor.Attributes);
                DbConnectionStringBuilderDescriptor descriptor2 = new DbConnectionStringBuilderDescriptor(descriptor.Name, descriptor.ComponentType, descriptor.PropertyType, isReadOnly, attributesFromCollection);
                descriptor2.RefreshOnChange = flag2;
                propertyDescriptors[displayName] = descriptor2;
            }
            base.GetProperties(propertyDescriptors);
        }

        public override bool Remove(string keyword)
        {
            Keywords keywords;
            ADP.CheckArgumentNull(keyword, "keyword");
            if (_keywords.TryGetValue(keyword, out keywords) && base.Remove(_validKeywords[(int)keywords]))
            {
                this.Reset(keywords);
                return true;
            }
            return false;
        }

        private void Reset(Keywords index)
        {
            switch (index)
            {
                case Keywords.DataSource:
                    this._dataSource = "";
                    return;

                case Keywords.FailoverPartner:
                    this._failoverPartner = "";
                    return;

                case Keywords.AttachDBFilename:
                    this._attachDBFilename = "";
                    return;

                case Keywords.InitialCatalog:
                    this._initialCatalog = "";
                    return;

                case Keywords.IntegratedSecurity:
                    this._integratedSecurity = false;
                    return;

                case Keywords.PersistSecurityInfo:
                    this._persistSecurityInfo = false;
                    return;

                case Keywords.UserID:
                    this._userID = "";
                    return;

                case Keywords.Password:
                    this._password = "";
                    return;

                case Keywords.Enlist:
                    this._enlist = true;
                    return;

                case Keywords.Pooling:
                    this._pooling = true;
                    return;

                case Keywords.MinPoolSize:
                    this._minPoolSize = 0;
                    return;

                case Keywords.MaxPoolSize:
                    this._maxPoolSize = 100;
                    return;

                case Keywords.AsynchronousProcessing:
                    this._asynchronousProcessing = false;
                    return;

                case Keywords.ConnectionReset:
                    this._connectionReset = true;
                    return;

                case Keywords.MultipleActiveResultSets:
                    this._multipleActiveResultSets = false;
                    return;

                case Keywords.Replication:
                    this._replication = false;
                    return;

                case Keywords.ConnectTimeout:
                    this._connectTimeout = 15;
                    return;

                case Keywords.Encrypt:
                    this._encrypt = false;
                    return;

                case Keywords.TrustServerCertificate:
                    this._trustServerCertificate = false;
                    return;

                case Keywords.LoadBalanceTimeout:
                    this._loadBalanceTimeout = 0;
                    return;

                case Keywords.NetworkLibrary:
                    this._networkLibrary = "";
                    return;

                case Keywords.PacketSize:
                    this._packetSize = 0x1f40;
                    return;

                case Keywords.TypeSystemVersion:
                    this._typeSystemVersion = "Latest";
                    return;

                case Keywords.ApplicationName:
                    this._applicationName = ".Net SqlClient Data Provider";
                    return;

                case Keywords.CurrentLanguage:
                    this._currentLanguage = "";
                    return;

                case Keywords.WorkstationID:
                    this._workstationID = "";
                    return;

                case Keywords.UserInstance:
                    this._userInstance = false;
                    return;

                case Keywords.ContextConnection:
                    this._contextConnection = false;
                    return;

                case Keywords.TransactionBinding:
                    this._transactionBinding = "Implicit Unbind";
                    return;

                case Keywords.ApplicationIntent:
                    this._applicationIntent = ApplicationIntent.ReadWrite;
                    return;

                case Keywords.MultiSubnetFailover:
                    this._multiSubnetFailover = false;
                    return;
            }
            throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
        }

        private void SetApplicationIntentValue(ApplicationIntent value)
        {
            base["ApplicationIntent"] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value);
        }

        private void SetValue(string keyword, bool value)
        {
            base[keyword] = value.ToString(null);
        }

        private void SetValue(string keyword, int value)
        {
            base[keyword] = value.ToString((IFormatProvider)null);
        }

        private void SetValue(string keyword, string value)
        {
            ADP.CheckArgumentNull(value, keyword);
            base[keyword] = value;
        }

        public override bool ShouldSerialize(string keyword)
        {
            Keywords keywords;
            ADP.CheckArgumentNull(keyword, "keyword");
            return (_keywords.TryGetValue(keyword, out keywords) && base.ShouldSerialize(_validKeywords[(int)keywords]));
        }

        public override bool TryGetValue(string keyword, out object value)
        {
            Keywords keywords;
            if (_keywords.TryGetValue(keyword, out keywords))
            {
                value = this.GetAt(keywords);
                return true;
            }
            value = null;
            return false;
        }

        // Properties
        [ResCategory("DataCategory_Initialization"), DisplayName("ApplicationIntent"), ResDescription("DbConnectionString_ApplicationIntent"), RefreshProperties(RefreshProperties.All)]
        public ApplicationIntent ApplicationIntent
        {
            get
            {
                return this._applicationIntent;
            }
            set
            {
                if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value))
                {
                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value);
                }
                this.SetApplicationIntentValue(value);
                this._applicationIntent = value;
            }
        }

        [RefreshProperties(RefreshProperties.All), DisplayName("Application Name"), ResCategory("DataCategory_Context"), ResDescription("DbConnectionString_ApplicationName")]
        public string ApplicationName
        {
            get
            {
                return this._applicationName;
            }
            set
            {
                this.SetValue("Application Name", value);
                this._applicationName = value;
            }
        }

        [DisplayName("Asynchronous Processing"), ResCategory("DataCategory_Initialization"), ResDescription("DbConnectionString_AsynchronousProcessing"), RefreshProperties(RefreshProperties.All)]
        public bool AsynchronousProcessing
        {
            get
            {
                return this._asynchronousProcessing;
            }
            set
            {
                this.SetValue("Asynchronous Processing", value);
                this._asynchronousProcessing = value;
            }
        }

        [Editor("System.Windows.Forms.Design.FileNameEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), DisplayName("AttachDbFilename"), ResCategory("DataCategory_Source"), ResDescription("DbConnectionString_AttachDBFilename"), RefreshProperties(RefreshProperties.All)]
        public string AttachDBFilename
        {
            get
            {
                return this._attachDBFilename;
            }
            set
            {
                this.SetValue("AttachDbFilename", value);
                this._attachDBFilename = value;
            }
        }

        [ResCategory("DataCategory_Pooling"), Browsable(false), DisplayName("Connection Reset"), Obsolete("ConnectionReset has been deprecated.  SqlConnection will ignore the 'connection reset' keyword and always reset the connection"), ResDescription("DbConnectionString_ConnectionReset"), RefreshProperties(RefreshProperties.All)]
        public bool ConnectionReset
        {
            get
            {
                return this._connectionReset;
            }
            set
            {
                this.SetValue("Connection Reset", value);
                this._connectionReset = value;
            }
        }

        [ResCategory("DataCategory_Initialization"), DisplayName("Connect Timeout"), RefreshProperties(RefreshProperties.All), ResDescription("DbConnectionString_ConnectTimeout")]
        public int ConnectTimeout
        {
            get
            {
                return this._connectTimeout;
            }
            set
            {
                if (value < 0)
                {
                    throw ADP.InvalidConnectionOptionValue("Connect Timeout");
                }
                this.SetValue("Connect Timeout", value);
                this._connectTimeout = value;
            }
        }

        [ResDescription("DbConnectionString_ContextConnection"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Source"), DisplayName("Context Connection")]
        public bool ContextConnection
        {
            get
            {
                return this._contextConnection;
            }
            set
            {
                this.SetValue("Context Connection", value);
                this._contextConnection = value;
            }
        }

        [RefreshProperties(RefreshProperties.All), DisplayName("Current Language"), ResCategory("DataCategory_Initialization"), ResDescription("DbConnectionString_CurrentLanguage")]
        public string CurrentLanguage
        {
            get
            {
                return this._currentLanguage;
            }
            set
            {
                this.SetValue("Current Language", value);
                this._currentLanguage = value;
            }
        }

        [ResDescription("DbConnectionString_DataSource"), DisplayName("Data Source"), RefreshProperties(RefreshProperties.All), TypeConverter(typeof(SqlDataSourceConverter)), ResCategory("DataCategory_Source")]
        public string DataSource
        {
            get
            {
                return this._dataSource;
            }
            set
            {
                this.SetValue("Data Source", value);
                this._dataSource = value;
            }
        }

        [ResCategory("DataCategory_Security"), ResDescription("DbConnectionString_Encrypt"), RefreshProperties(RefreshProperties.All), DisplayName("Encrypt")]
        public bool Encrypt
        {
            get
            {
                return this._encrypt;
            }
            set
            {
                this.SetValue("Encrypt", value);
                this._encrypt = value;
            }
        }

        [ResCategory("DataCategory_Pooling"), ResDescription("DbConnectionString_Enlist"), RefreshProperties(RefreshProperties.All), DisplayName("Enlist")]
        public bool Enlist
        {
            get
            {
                return this._enlist;
            }
            set
            {
                this.SetValue("Enlist", value);
                this._enlist = value;
            }
        }

        [ResDescription("DbConnectionString_FailoverPartner"), ResCategory("DataCategory_Source"), RefreshProperties(RefreshProperties.All), TypeConverter(typeof(SqlDataSourceConverter)), DisplayName("Failover Partner")]
        public string FailoverPartner
        {
            get
            {
                return this._failoverPartner;
            }
            set
            {
                this.SetValue("Failover Partner", value);
                this._failoverPartner = value;
            }
        }

        [ResCategory("DataCategory_Source"), ResDescription("DbConnectionString_InitialCatalog"), RefreshProperties(RefreshProperties.All), TypeConverter(typeof(SqlInitialCatalogConverter)), DisplayName("Initial Catalog")]
        public string InitialCatalog
        {
            get
            {
                return this._initialCatalog;
            }
            set
            {
                this.SetValue("Initial Catalog", value);
                this._initialCatalog = value;
            }
        }

        [DisplayName("Integrated Security"), ResCategory("DataCategory_Security"), ResDescription("DbConnectionString_IntegratedSecurity"), RefreshProperties(RefreshProperties.All)]
        public bool IntegratedSecurity
        {
            get
            {
                return this._integratedSecurity;
            }
            set
            {
                this.SetValue("Integrated Security", value);
                this._integratedSecurity = value;
            }
        }

        public override bool IsFixedSize
        {
            get
            {
                return true;
            }
        }

        public override object this[string keyword]
        {
            get
            {
                Keywords index = this.GetIndex(keyword);
                return this.GetAt(index);
            }
            set
            {
                if (value != null)
                {
                    switch (this.GetIndex(keyword))
                    {
                        case Keywords.DataSource:
                            this.DataSource = ConvertToString(value);
                            return;

                        case Keywords.FailoverPartner:
                            this.FailoverPartner = ConvertToString(value);
                            return;

                        case Keywords.AttachDBFilename:
                            this.AttachDBFilename = ConvertToString(value);
                            return;

                        case Keywords.InitialCatalog:
                            this.InitialCatalog = ConvertToString(value);
                            return;

                        case Keywords.IntegratedSecurity:
                            this.IntegratedSecurity = ConvertToIntegratedSecurity(value);
                            return;

                        case Keywords.PersistSecurityInfo:
                            this.PersistSecurityInfo = ConvertToBoolean(value);
                            return;

                        case Keywords.UserID:
                            this.UserID = ConvertToString(value);
                            return;

                        case Keywords.Password:
                            this.Password = ConvertToString(value);
                            return;

                        case Keywords.Enlist:
                            this.Enlist = ConvertToBoolean(value);
                            return;

                        case Keywords.Pooling:
                            this.Pooling = ConvertToBoolean(value);
                            return;

                        case Keywords.MinPoolSize:
                            this.MinPoolSize = ConvertToInt32(value);
                            return;

                        case Keywords.MaxPoolSize:
                            this.MaxPoolSize = ConvertToInt32(value);
                            return;

                        case Keywords.AsynchronousProcessing:
                            this.AsynchronousProcessing = ConvertToBoolean(value);
                            return;

                        case Keywords.ConnectionReset:
                            this.ConnectionReset = ConvertToBoolean(value);
                            return;

                        case Keywords.MultipleActiveResultSets:
                            this.MultipleActiveResultSets = ConvertToBoolean(value);
                            return;

                        case Keywords.Replication:
                            this.Replication = ConvertToBoolean(value);
                            return;

                        case Keywords.ConnectTimeout:
                            this.ConnectTimeout = ConvertToInt32(value);
                            return;

                        case Keywords.Encrypt:
                            this.Encrypt = ConvertToBoolean(value);
                            return;

                        case Keywords.TrustServerCertificate:
                            this.TrustServerCertificate = ConvertToBoolean(value);
                            return;

                        case Keywords.LoadBalanceTimeout:
                            this.LoadBalanceTimeout = ConvertToInt32(value);
                            return;

                        case Keywords.NetworkLibrary:
                            this.NetworkLibrary = ConvertToString(value);
                            return;

                        case Keywords.PacketSize:
                            this.PacketSize = ConvertToInt32(value);
                            return;

                        case Keywords.TypeSystemVersion:
                            this.TypeSystemVersion = ConvertToString(value);
                            return;

                        case Keywords.ApplicationName:
                            this.ApplicationName = ConvertToString(value);
                            return;

                        case Keywords.CurrentLanguage:
                            this.CurrentLanguage = ConvertToString(value);
                            return;

                        case Keywords.WorkstationID:
                            this.WorkstationID = ConvertToString(value);
                            return;

                        case Keywords.UserInstance:
                            this.UserInstance = ConvertToBoolean(value);
                            return;

                        case Keywords.ContextConnection:
                            this.ContextConnection = ConvertToBoolean(value);
                            return;

                        case Keywords.TransactionBinding:
                            this.TransactionBinding = ConvertToString(value);
                            return;

                        case Keywords.ApplicationIntent:
                            this.ApplicationIntent = ConvertToApplicationIntent(keyword, value);
                            return;

                        case Keywords.MultiSubnetFailover:
                            this.MultiSubnetFailover = ConvertToBoolean(value);
                            return;
                    }
                    throw ADP.KeywordNotSupported(keyword);
                }
                this.Remove(keyword);
            }
        }

        public override ICollection Keys
        {
            get
            {
                return new ReadOnlyCollection<string>(_validKeywords);
            }
        }

        [DisplayName("Load Balance Timeout"), ResDescription("DbConnectionString_LoadBalanceTimeout"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Pooling")]
        public int LoadBalanceTimeout
        {
            get
            {
                return this._loadBalanceTimeout;
            }
            set
            {
                if (value < 0)
                {
                    throw ADP.InvalidConnectionOptionValue("Load Balance Timeout");
                }
                this.SetValue("Load Balance Timeout", value);
                this._loadBalanceTimeout = value;
            }
        }

        [DisplayName("Max Pool Size"), ResCategory("DataCategory_Pooling"), ResDescription("DbConnectionString_MaxPoolSize"), RefreshProperties(RefreshProperties.All)]
        public int MaxPoolSize
        {
            get
            {
                return this._maxPoolSize;
            }
            set
            {
                if (value < 1)
                {
                    throw ADP.InvalidConnectionOptionValue("Max Pool Size");
                }
                this.SetValue("Max Pool Size", value);
                this._maxPoolSize = value;
            }
        }

        [ResDescription("DbConnectionString_MinPoolSize"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Pooling"), DisplayName("Min Pool Size")]
        public int MinPoolSize
        {
            get
            {
                return this._minPoolSize;
            }
            set
            {
                if (value < 0)
                {
                    throw ADP.InvalidConnectionOptionValue("Min Pool Size");
                }
                this.SetValue("Min Pool Size", value);
                this._minPoolSize = value;
            }
        }

        [DisplayName("MultipleActiveResultSets"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Advanced"), ResDescription("DbConnectionString_MultipleActiveResultSets")]
        public bool MultipleActiveResultSets
        {
            get
            {
                return this._multipleActiveResultSets;
            }
            set
            {
                this.SetValue("MultipleActiveResultSets", value);
                this._multipleActiveResultSets = value;
            }
        }

        [ResDescription("DbConnectionString_MultiSubnetFailover"), DisplayName("MultiSubnetFailover"), ResCategory("DataCategory_Source"), RefreshProperties(RefreshProperties.All)]
        public bool MultiSubnetFailover
        {
            get
            {
                return this._multiSubnetFailover;
            }
            set
            {
                this.SetValue("MultiSubnetFailover", value);
                this._multiSubnetFailover = value;
            }
        }

        [ResCategory("DataCategory_Advanced"), DisplayName("Network Library"), TypeConverter(typeof(NetworkLibraryConverter)), ResDescription("DbConnectionString_NetworkLibrary"), RefreshProperties(RefreshProperties.All)]
        public string NetworkLibrary
        {
            get
            {
                return this._networkLibrary;
            }
            set
            {
                if (value != null)
                {
                    switch (value.Trim().ToLower(CultureInfo.InvariantCulture))
                    {
                        case "dbmsadsn":
                            value = "dbmsadsn";
                            goto Label_011F;

                        case "dbmsvinn":
                            value = "dbmsvinn";
                            goto Label_011F;

                        case "dbmsspxn":
                            value = "dbmsspxn";
                            goto Label_011F;

                        case "dbmsrpcn":
                            value = "dbmsrpcn";
                            goto Label_011F;

                        case "dbnmpntw":
                            value = "dbnmpntw";
                            goto Label_011F;

                        case "dbmslpcn":
                            value = "dbmslpcn";
                            goto Label_011F;

                        case "dbmssocn":
                            value = "dbmssocn";
                            goto Label_011F;

                        case "dbmsgnet":
                            value = "dbmsgnet";
                            goto Label_011F;
                    }
                    throw ADP.InvalidConnectionOptionValue("Network Library");
                }
            Label_011F:
                this.SetValue("Network Library", value);
                this._networkLibrary = value;
            }
        }

        [ResCategory("DataCategory_Advanced"), RefreshProperties(RefreshProperties.All), ResDescription("DbConnectionString_PacketSize"), DisplayName("Packet Size")]
        public int PacketSize
        {
            get
            {
                return this._packetSize;
            }
            set
            {
                if ((value < 0x200) || (0x8000 < value))
                {
                    throw SQL.InvalidPacketSizeValue();
                }
                this.SetValue("Packet Size", value);
                this._packetSize = value;
            }
        }

        [PasswordPropertyText(true), DisplayName("Password"), ResDescription("DbConnectionString_Password"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Security")]
        public string Password
        {
            get
            {
                return this._password;
            }
            set
            {
                this.SetValue("Password", value);
                this._password = value;
            }
        }

        [ResDescription("DbConnectionString_PersistSecurityInfo"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Security"), DisplayName("Persist Security Info")]
        public bool PersistSecurityInfo
        {
            get
            {
                return this._persistSecurityInfo;
            }
            set
            {
                this.SetValue("Persist Security Info", value);
                this._persistSecurityInfo = value;
            }
        }

        [ResDescription("DbConnectionString_Pooling"), RefreshProperties(RefreshProperties.All), DisplayName("Pooling"), ResCategory("DataCategory_Pooling")]
        public bool Pooling
        {
            get
            {
                return this._pooling;
            }
            set
            {
                this.SetValue("Pooling", value);
                this._pooling = value;
            }
        }

        [DisplayName("Replication"), ResDescription("DbConnectionString_Replication"), ResCategory("DataCategory_Replication"), RefreshProperties(RefreshProperties.All)]
        public bool Replication
        {
            get
            {
                return this._replication;
            }
            set
            {
                this.SetValue("Replication", value);
                this._replication = value;
            }
        }

        [ResCategory("DataCategory_Advanced"), ResDescription("DbConnectionString_TransactionBinding"), DisplayName("Transaction Binding"), RefreshProperties(RefreshProperties.All)]
        public string TransactionBinding
        {
            get
            {
                return this._transactionBinding;
            }
            set
            {
                this.SetValue("Transaction Binding", value);
                this._transactionBinding = value;
            }
        }

        [ResDescription("DbConnectionString_TrustServerCertificate"), ResCategory("DataCategory_Security"), RefreshProperties(RefreshProperties.All), DisplayName("TrustServerCertificate")]
        public bool TrustServerCertificate
        {
            get
            {
                return this._trustServerCertificate;
            }
            set
            {
                this.SetValue("TrustServerCertificate", value);
                this._trustServerCertificate = value;
            }
        }

        [ResDescription("DbConnectionString_TypeSystemVersion"), ResCategory("DataCategory_Advanced"), RefreshProperties(RefreshProperties.All), DisplayName("Type System Version")]
        public string TypeSystemVersion
        {
            get
            {
                return this._typeSystemVersion;
            }
            set
            {
                this.SetValue("Type System Version", value);
                this._typeSystemVersion = value;
            }
        }

        [ResCategory("DataCategory_Security"), RefreshProperties(RefreshProperties.All), ResDescription("DbConnectionString_UserID"), DisplayName("User ID")]
        public string UserID
        {
            get
            {
                return this._userID;
            }
            set
            {
                this.SetValue("User ID", value);
                this._userID = value;
            }
        }

        [RefreshProperties(RefreshProperties.All), ResDescription("DbConnectionString_UserInstance"), DisplayName("User Instance"), ResCategory("DataCategory_Source")]
        public bool UserInstance
        {
            get
            {
                return this._userInstance;
            }
            set
            {
                this.SetValue("User Instance", value);
                this._userInstance = value;
            }
        }

        public override ICollection Values
        {
            get
            {
                object[] items = new object[_validKeywords.Length];
                for (int i = 0; i < items.Length; i++)
                {
                    items[i] = this.GetAt((Keywords)i);
                }
                return new ReadOnlyCollection<object>(items);
            }
        }

        [ResDescription("DbConnectionString_WorkstationID"), DisplayName("Workstation ID"), RefreshProperties(RefreshProperties.All), ResCategory("DataCategory_Context")]
        public string WorkstationID
        {
            get
            {
                return this._workstationID;
            }
            set
            {
                this.SetValue("Workstation ID", value);
                this._workstationID = value;
            }
        }

        // Nested Types
        private enum Keywords
        {
            DataSource,
            FailoverPartner,
            AttachDBFilename,
            InitialCatalog,
            IntegratedSecurity,
            PersistSecurityInfo,
            UserID,
            Password,
            Enlist,
            Pooling,
            MinPoolSize,
            MaxPoolSize,
            AsynchronousProcessing,
            ConnectionReset,
            MultipleActiveResultSets,
            Replication,
            ConnectTimeout,
            Encrypt,
            TrustServerCertificate,
            LoadBalanceTimeout,
            NetworkLibrary,
            PacketSize,
            TypeSystemVersion,
            ApplicationName,
            CurrentLanguage,
            WorkstationID,
            UserInstance,
            ContextConnection,
            TransactionBinding,
            ApplicationIntent,
            MultiSubnetFailover,
            KeywordsCount
        }

        private sealed class NetworkLibraryConverter : TypeConverter
        {
            // Fields
            private TypeConverter.StandardValuesCollection _standardValues;
            private const string NamedPipes = "Named Pipes (DBNMPNTW)";
            private const string SharedMemory = "Shared Memory (DBMSLPCN)";
            private const string TCPIP = "TCP/IP (DBMSSOCN)";
            private const string VIA = "VIA (DBMSGNET)";

            // Methods
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                if (!(typeof(string) == sourceType))
                {
                    return base.CanConvertFrom(context, sourceType);
                }
                return true;
            }

            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
            {
                if (!(typeof(string) == destinationType))
                {
                    return base.CanConvertTo(context, destinationType);
                }
                return true;
            }

            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                string x = value as string;
                if (x == null)
                {
                    return base.ConvertFrom(context, culture, value);
                }
                x = x.Trim();
                if (StringComparer.OrdinalIgnoreCase.Equals(x, "Named Pipes (DBNMPNTW)"))
                {
                    return "dbnmpntw";
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(x, "Shared Memory (DBMSLPCN)"))
                {
                    return "dbmslpcn";
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(x, "TCP/IP (DBMSSOCN)"))
                {
                    return "dbmssocn";
                }
                if (StringComparer.OrdinalIgnoreCase.Equals(x, "VIA (DBMSGNET)"))
                {
                    return "dbmsgnet";
                }
                return x;
            }

            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
            {
                string str2 = value as string;
                if ((str2 == null) || !(destinationType == typeof(string)))
                {
                    return base.ConvertTo(context, culture, value, destinationType);
                }
                string str = str2.Trim().ToLower(CultureInfo.InvariantCulture);
                if (str == null)
                {
                    return str2;
                }
                if (!(str == "dbnmpntw"))
                {
                    if (str == "dbmslpcn")
                    {
                        return "Shared Memory (DBMSLPCN)";
                    }
                    if (str == "dbmssocn")
                    {
                        return "TCP/IP (DBMSSOCN)";
                    }
                    if (str == "dbmsgnet")
                    {
                        return "VIA (DBMSGNET)";
                    }
                    return str2;
                }
                return "Named Pipes (DBNMPNTW)";
            }

            public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                if (context != null)
                {
                    object instance = context.Instance;
                }
                TypeConverter.StandardValuesCollection valuess = this._standardValues;
                if (valuess == null)
                {
                    string[] values = new string[] { "Named Pipes (DBNMPNTW)", "Shared Memory (DBMSLPCN)", "TCP/IP (DBMSSOCN)", "VIA (DBMSGNET)" };
                    valuess = new TypeConverter.StandardValuesCollection(values);
                    this._standardValues = valuess;
                }
                return valuess;
            }

            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            {
                return false;
            }

            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            {
                return true;
            }
        }

        internal sealed class SqlConnectionStringBuilderConverter : ExpandableObjectConverter
        {
            // Methods
            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
            {
                return ((typeof(InstanceDescriptor) == destinationType) || base.CanConvertTo(context, destinationType));
            }

            public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
            {
                if (destinationType == null)
                {
                    throw ADP.ArgumentNull("destinationType");
                }
                if (typeof(InstanceDescriptor) == destinationType)
                {
                    SqlConnectionStringBuilder options = value as SqlConnectionStringBuilder;
                    if (options != null)
                    {
                        return this.ConvertToInstanceDescriptor(options);
                    }
                }
                return base.ConvertTo(context, culture, value, destinationType);
            }

            private InstanceDescriptor ConvertToInstanceDescriptor(SqlConnectionStringBuilder options)
            {
                Type[] types = new Type[] { typeof(string) };
                return new InstanceDescriptor(typeof(SqlConnectionStringBuilder).GetConstructor(types), new object[] { options.ConnectionString });
            }
        }

        private sealed class SqlDataSourceConverter : StringConverter
        {
            // Fields
            private TypeConverter.StandardValuesCollection _standardValues;

            // Methods
            public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                TypeConverter.StandardValuesCollection valuess = this._standardValues;
                if (this._standardValues == null)
                {
                    DataTable dataSources = SqlClientFactory.Instance.CreateDataSourceEnumerator().GetDataSources();
                    DataColumn column2 = dataSources.Columns["ServerName"];
                    DataColumn column = dataSources.Columns["InstanceName"];
                    DataRowCollection rows = dataSources.Rows;
                    string[] array = new string[rows.Count];
                    for (int i = 0; i < array.Length; i++)
                    {
                        string str2 = rows[i][column2] as string;
                        string str = rows[i][column] as string;
                        if (((str == null) || (str.Length == 0)) || ("MSSQLSERVER" == str))
                        {
                            array[i] = str2;
                        }
                        else
                        {
                            array[i] = str2 + @"\" + str;
                        }
                    }
                    Array.Sort<string>(array);
                    valuess = new TypeConverter.StandardValuesCollection(array);
                    this._standardValues = valuess;
                }
                return valuess;
            }

            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            {
                return false;
            }

            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            {
                return true;
            }
        }

        private sealed class SqlInitialCatalogConverter : StringConverter
        {
            // Methods
            public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                if (!this.GetStandardValuesSupportedInternal(context))
                {
                    return null;
                }
                List<string> values = new List<string>();
                try
                {
                    SqlConnectionStringBuilder instance = (SqlConnectionStringBuilder)context.Instance;
                    using (SqlConnection connection = new SqlConnection())
                    {
                        connection.ConnectionString = instance.ConnectionString;
                        connection.Open();
                        foreach (DataRow row in connection.GetSchema("DATABASES").Rows)
                        {
                            string item = (string)row["database_name"];
                            values.Add(item);
                        }
                    }
                }
                catch (SqlException exception)
                {
                    ADP.TraceExceptionWithoutRethrow(exception);
                }
                return new TypeConverter.StandardValuesCollection(values);
            }

            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            {
                return false;
            }

            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            {
                return this.GetStandardValuesSupportedInternal(context);
            }

            private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context)
            {
                bool flag = false;
                if (context == null)
                {
                    return flag;
                }
                SqlConnectionStringBuilder instance = context.Instance as SqlConnectionStringBuilder;
                if (((instance == null) || (0 >= instance.DataSource.Length)) || (!instance.IntegratedSecurity && (0 >= instance.UserID.Length)))
                {
                    return flag;
                }
                return true;
            }
        }
    }


发现这个类是继承类:DbConnectionStringBuilder

那么,在看看这个类的源代码:

public class DbConnectionStringBuilder : IDictionary, ICollection, IEnumerable, ICustomTypeDescriptor
{
    // Fields
    private bool _browsableConnectionString;
    private string _connectionString;
    private Dictionary<string, object> _currentValues;
    internal readonly int _objectID;
    private static int _objectTypeCount;
    private PropertyDescriptorCollection _propertyDescriptors;
    private readonly bool UseOdbcRules;

    // Methods
    public DbConnectionStringBuilder()
    {
        this._connectionString = "";
        this._browsableConnectionString = true;
        this._objectID = Interlocked.Increment(ref _objectTypeCount);
    }

    public DbConnectionStringBuilder(bool useOdbcRules)
    {
        this._connectionString = "";
        this._browsableConnectionString = true;
        this._objectID = Interlocked.Increment(ref _objectTypeCount);
        this.UseOdbcRules = useOdbcRules;
    }

    public void Add(string keyword, object value)
    {
        this[keyword] = value;
    }

    public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value)
    {
        DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, false);
    }

    public static void AppendKeyValuePair(StringBuilder builder, string keyword, string value, bool useOdbcRules)
    {
        DbConnectionOptions.AppendKeyValuePairBuilder(builder, keyword, value, useOdbcRules);
    }

    public virtual void Clear()
    {
        Bid.Trace("<comm.DbConnectionStringBuilder.Clear|API>\n");
        this._connectionString = "";
        this._propertyDescriptors = null;
        this.CurrentValues.Clear();
    }

    protected internal void ClearPropertyDescriptors()
    {
        this._propertyDescriptors = null;
    }

    public virtual bool ContainsKey(string keyword)
    {
        ADP.CheckArgumentNull(keyword, "keyword");
        return this.CurrentValues.ContainsKey(keyword);
    }

    public virtual bool EquivalentTo(DbConnectionStringBuilder connectionStringBuilder)
    {
        ADP.CheckArgumentNull(connectionStringBuilder, "connectionStringBuilder");
        Bid.Trace("<comm.DbConnectionStringBuilder.EquivalentTo|API> %d#, connectionStringBuilder=%d#\n", this.ObjectID, connectionStringBuilder.ObjectID);
        if ((base.GetType() != connectionStringBuilder.GetType()) || (this.CurrentValues.Count != connectionStringBuilder.CurrentValues.Count))
        {
            return false;
        }
        foreach (KeyValuePair<string, object> pair in this.CurrentValues)
        {
            object obj2;
            if (!connectionStringBuilder.CurrentValues.TryGetValue(pair.Key, out obj2) || !pair.Value.Equals(obj2))
            {
                return false;
            }
        }
        return true;
    }

    internal Attribute[] GetAttributesFromCollection(AttributeCollection collection)
    {
        Attribute[] array = new Attribute[collection.Count];
        collection.CopyTo(array, 0);
        return array;
    }

    private PropertyDescriptorCollection GetProperties()
    {
        PropertyDescriptorCollection descriptors = this._propertyDescriptors;
        if (descriptors == null)
        {
            IntPtr ptr;
            Bid.ScopeEnter(out ptr, "<comm.DbConnectionStringBuilder.GetProperties|INFO> %d#", this.ObjectID);
            try
            {
                Hashtable propertyDescriptors = new Hashtable(StringComparer.OrdinalIgnoreCase);
                this.GetProperties(propertyDescriptors);
                PropertyDescriptor[] array = new PropertyDescriptor[propertyDescriptors.Count];
                propertyDescriptors.Values.CopyTo(array, 0);
                descriptors = new PropertyDescriptorCollection(array);
                this._propertyDescriptors = descriptors;
            }
            finally
            {
                Bid.ScopeLeave(ref ptr);
            }
        }
        return descriptors;
    }

    protected virtual void GetProperties(Hashtable propertyDescriptors)
    {
        IntPtr ptr;
        Bid.ScopeEnter(out ptr, "<comm.DbConnectionStringBuilder.GetProperties|API> %d#", this.ObjectID);
        try
        {
            Attribute[] attributesFromCollection;
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(this, true))
            {
                if ("ConnectionString" != descriptor.Name)
                {
                    string displayName = descriptor.DisplayName;
                    if (!propertyDescriptors.ContainsKey(displayName))
                    {
                        attributesFromCollection = this.GetAttributesFromCollection(descriptor.Attributes);
                        PropertyDescriptor descriptor3 = new DbConnectionStringBuilderDescriptor(descriptor.Name, descriptor.ComponentType, descriptor.PropertyType, descriptor.IsReadOnly, attributesFromCollection);
                        propertyDescriptors[displayName] = descriptor3;
                    }
                }
                else
                {
                    if (this.BrowsableConnectionString)
                    {
                        propertyDescriptors["ConnectionString"] = descriptor;
                        continue;
                    }
                    propertyDescriptors.Remove("ConnectionString");
                }
            }
            if (!this.IsFixedSize)
            {
                attributesFromCollection = null;
                foreach (string str in this.Keys)
                {
                    Type type;
                    if (propertyDescriptors.ContainsKey(str))
                    {
                        continue;
                    }
                    object obj2 = this[str];
                    if (obj2 != null)
                    {
                        type = obj2.GetType();
                        if (typeof(string) == type)
                        {
                            int num;
                            if (int.TryParse((string) obj2, out num))
                            {
                                type = typeof(int);
                            }
                            else
                            {
                                bool flag;
                                if (bool.TryParse((string) obj2, out flag))
                                {
                                    type = typeof(bool);
                                }
                            }
                        }
                    }
                    else
                    {
                        type = typeof(string);
                    }
                    Attribute[] attributes = attributesFromCollection;
                    if (StringComparer.OrdinalIgnoreCase.Equals("Password", str) || StringComparer.OrdinalIgnoreCase.Equals("pwd", str))
                    {
                        attributes = new Attribute[] { BrowsableAttribute.Yes, PasswordPropertyTextAttribute.Yes, new ResCategoryAttribute("DataCategory_Security"), RefreshPropertiesAttribute.All };
                    }
                    else if (attributesFromCollection == null)
                    {
                        attributesFromCollection = new Attribute[] { BrowsableAttribute.Yes, RefreshPropertiesAttribute.All };
                        attributes = attributesFromCollection;
                    }
                    PropertyDescriptor descriptor2 = new DbConnectionStringBuilderDescriptor(str, base.GetType(), type, false, attributes);
                    propertyDescriptors[str] = descriptor2;
                }
            }
        }
        finally
        {
            Bid.ScopeLeave(ref ptr);
        }
    }

    private PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        PropertyDescriptorCollection properties = this.GetProperties();
        if ((attributes == null) || (attributes.Length == 0))
        {
            return properties;
        }
        PropertyDescriptor[] sourceArray = new PropertyDescriptor[properties.Count];
        int index = 0;
        foreach (PropertyDescriptor descriptor in properties)
        {
            bool flag = true;
            foreach (Attribute attribute in attributes)
            {
                Attribute attribute2 = descriptor.Attributes[attribute.GetType()];
                if (((attribute2 == null) && !attribute.IsDefaultAttribute()) || !attribute2.Match(attribute))
                {
                    flag = false;
                    break;
                }
            }
            if (flag)
            {
                sourceArray[index] = descriptor;
                index++;
            }
        }
        PropertyDescriptor[] destinationArray = new PropertyDescriptor[index];
        Array.Copy(sourceArray, destinationArray, index);
        return new PropertyDescriptorCollection(destinationArray);
    }

    private string ObjectToString(object keyword)
    {
        string str;
        try
        {
            str = (string) keyword;
        }
        catch (InvalidCastException)
        {
            throw new ArgumentException("keyword", "not a string");
        }
        return str;
    }

    public virtual bool Remove(string keyword)
    {
        Bid.Trace("<comm.DbConnectionStringBuilder.Remove|API> %d#, keyword='%ls'\n", this.ObjectID, keyword);
        ADP.CheckArgumentNull(keyword, "keyword");
        if (this.CurrentValues.Remove(keyword))
        {
            this._connectionString = null;
            this._propertyDescriptors = null;
            return true;
        }
        return false;
    }

    public virtual bool ShouldSerialize(string keyword)
    {
        ADP.CheckArgumentNull(keyword, "keyword");
        return this.CurrentValues.ContainsKey(keyword);
    }

    void ICollection.CopyTo(Array array, int index)
    {
        Bid.Trace("<comm.DbConnectionStringBuilder.ICollection.CopyTo|API> %d#\n", this.ObjectID);
        this.Collection.CopyTo(array, index);
    }

    void IDictionary.Add(object keyword, object value)
    {
        this.Add(this.ObjectToString(keyword), value);
    }

    bool IDictionary.Contains(object keyword)
    {
        return this.ContainsKey(this.ObjectToString(keyword));
    }

    IDictionaryEnumerator IDictionary.GetEnumerator()
    {
        Bid.Trace("<comm.DbConnectionStringBuilder.IDictionary.GetEnumerator|API> %d#\n", this.ObjectID);
        return this.Dictionary.GetEnumerator();
    }

    void IDictionary.Remove(object keyword)
    {
        this.Remove(this.ObjectToString(keyword));
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        Bid.Trace("<comm.DbConnectionStringBuilder.IEnumerable.GetEnumerator|API> %d#\n", this.ObjectID);
        return this.Collection.GetEnumerator();
    }

    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
        return TypeDescriptor.GetAttributes(this, true);
    }

    string ICustomTypeDescriptor.GetClassName()
    {
        return TypeDescriptor.GetClassName(this, true);
    }

    string ICustomTypeDescriptor.GetComponentName()
    {
        return TypeDescriptor.GetComponentName(this, true);
    }

    TypeConverter ICustomTypeDescriptor.GetConverter()
    {
        return TypeDescriptor.GetConverter(this, true);
    }

    EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
    {
        return TypeDescriptor.GetDefaultEvent(this, true);
    }

    PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
    {
        return TypeDescriptor.GetDefaultProperty(this, true);
    }

    object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
    {
        return TypeDescriptor.GetEditor(this, editorBaseType, true);
    }

    EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
    {
        return TypeDescriptor.GetEvents(this, true);
    }

    EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
    {
        return TypeDescriptor.GetEvents(this, attributes, true);
    }

    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
    {
        return this.GetProperties();
    }

    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
    {
        return this.GetProperties(attributes);
    }

    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }

    public override string ToString()
    {
        return this.ConnectionString;
    }

    public virtual bool TryGetValue(string keyword, out object value)
    {
        ADP.CheckArgumentNull(keyword, "keyword");
        return this.CurrentValues.TryGetValue(keyword, out value);
    }

    // Properties
    [DesignOnly(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public bool BrowsableConnectionString
    {
        get
        {
            return this._browsableConnectionString;
        }
        set
        {
            this._browsableConnectionString = value;
            this._propertyDescriptors = null;
        }
    }

    private ICollection Collection
    {
        get
        {
            return this.CurrentValues;
        }
    }

    [RefreshProperties(RefreshProperties.All), ResDescription("DbConnectionString_ConnectionString"), ResCategory("DataCategory_Data")]
    public string ConnectionString
    {
        get
        {
            Bid.Trace("<comm.DbConnectionStringBuilder.get_ConnectionString|API> %d#\n", this.ObjectID);
            string str = this._connectionString;
            if (str == null)
            {
                StringBuilder builder = new StringBuilder();
                foreach (string str2 in this.Keys)
                {
                    object obj2;
                    if (this.ShouldSerialize(str2) && this.TryGetValue(str2, out obj2))
                    {
                        string str3 = (obj2 != null) ? Convert.ToString(obj2, CultureInfo.InvariantCulture) : null;
                        AppendKeyValuePair(builder, str2, str3, this.UseOdbcRules);
                    }
                }
                str = builder.ToString();
                this._connectionString = str;
            }
            return str;
        }
        set
        {
            Bid.Trace("<comm.DbConnectionStringBuilder.set_ConnectionString|API> %d#\n", this.ObjectID);
            DbConnectionOptions options = new DbConnectionOptions(value, null, this.UseOdbcRules);
            string connectionString = this.ConnectionString;
            this.Clear();
            try
            {
                for (NameValuePair pair = options.KeyChain; pair != null; pair = pair.Next)
                {
                    if (pair.Value != null)
                    {
                        this[pair.Name] = pair.Value;
                    }
                    else
                    {
                        this.Remove(pair.Name);
                    }
                }
                this._connectionString = null;
            }
            catch (ArgumentException)
            {
                this.ConnectionString = connectionString;
                this._connectionString = connectionString;
                throw;
            }
        }
    }

    [Browsable(false)]
    public virtual int Count
    {
        get
        {
            return this.CurrentValues.Count;
        }
    }

    private Dictionary<string, object> CurrentValues
    {
        get
        {
            Dictionary<string, object> dictionary = this._currentValues;
            if (dictionary == null)
            {
                dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
                this._currentValues = dictionary;
            }
            return dictionary;
        }
    }

    private IDictionary Dictionary
    {
        get
        {
            return this.CurrentValues;
        }
    }

    [Browsable(false)]
    public virtual bool IsFixedSize
    {
        get
        {
            return false;
        }
    }

    [Browsable(false)]
    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    [Browsable(false)]
    public virtual object this[string keyword]
    {
        get
        {
            object obj2;
            Bid.Trace("<comm.DbConnectionStringBuilder.get_Item|API> %d#, keyword='%ls'\n", this.ObjectID, keyword);
            ADP.CheckArgumentNull(keyword, "keyword");
            if (!this.CurrentValues.TryGetValue(keyword, out obj2))
            {
                throw ADP.KeywordNotSupported(keyword);
            }
            return obj2;
        }
        set
        {
            ADP.CheckArgumentNull(keyword, "keyword");
            bool flag = false;
            if (value != null)
            {
                string str = DbConnectionStringBuilderUtil.ConvertToString(value);
                DbConnectionOptions.ValidateKeyValuePair(keyword, str);
                flag = this.CurrentValues.ContainsKey(keyword);
                this.CurrentValues[keyword] = str;
            }
            else
            {
                flag = this.Remove(keyword);
            }
            this._connectionString = null;
            if (flag)
            {
                this._propertyDescriptors = null;
            }
        }
    }

    [Browsable(false)]
    public virtual ICollection Keys
    {
        get
        {
            Bid.Trace("<comm.DbConnectionStringBuilder.Keys|API> %d#\n", this.ObjectID);
            return this.Dictionary.Keys;
        }
    }

    internal int ObjectID
    {
        get
        {
            return this._objectID;
        }
    }

    bool ICollection.IsSynchronized
    {
        get
        {
            return this.Collection.IsSynchronized;
        }
    }

    object ICollection.SyncRoot
    {
        get
        {
            return this.Collection.SyncRoot;
        }
    }

    object IDictionary.this[object keyword]
    {
        get
        {
            return this[this.ObjectToString(keyword)];
        }
        set
        {
            this[this.ObjectToString(keyword)] = value;
        }
    }

    [Browsable(false)]
    public virtual ICollection Values
    {
        get
        {
            Bid.Trace("<comm.DbConnectionStringBuilder.Values|API> %d#\n", this.ObjectID);
            ICollection<string> keys = (ICollection<string>) this.Keys;
            IEnumerator<string> enumerator = keys.GetEnumerator();
            object[] items = new object[keys.Count];
            for (int i = 0; i < items.Length; i++)
            {
                enumerator.MoveNext();
                items[i] = this[enumerator.Current];
            }
            return new ReadOnlyCollection<object>(items);
        }
    }
}

 
Collapse Methods


关于数据库参数的配置来自于一个枚举:

private enum Keywords
        {
            DataSource,//要连接到的 SQL Server 实例的名称或网络地址
            FailoverPartner,//在主服务器停机时要连接到的伙伴服务器的名称或地址
            AttachDBFilename,//包含主数据文件名称的字符串。该字符串包括可附加数据库的完整路径名
            InitialCatalog,//与该连接关联的数据库的名称
            IntegratedSecurity,//一个布尔值,该值指示是否在连接中指定用户 ID 和密码(值为 false 时),或者是否使用当前的 Windows 帐户凭据进行身份验证(值为 true 时)
            PersistSecurityInfo,//一个布尔值,该值指示如果连接是打开的或者一直处于打开状态,那么安全敏感信息(如密码)是否将不作为连接的一部分返回
            UserID,//连接到 SQL Server 时要使用的用户 ID
            Password,//SQL Server 帐户的密码
            Enlist,//一个布尔值,该值指示 SQL Server 连接池程序是否在创建线程的当前事务上下文中自动登记连接
            Pooling,//一个布尔值,该值指示每次请求连接时该连接是汇入连接池还是显式打开
            MinPoolSize,//针对此特定连接字符串连接池中所允许的最小连接数
            MaxPoolSize,//针对此特定连接字符串连接池中所允许的最大连接数
            AsynchronousProcessing,//一个布尔值,该值指定使用此连接字符串创建的连接是否允许异步处理
            ConnectionReset,//一个布尔值,该值指示在从连接池中提取连接时是否重置连接(已过时)
            MultipleActiveResultSets,//一个布尔值,该值指示多活动结果集是否可与关联的连接相关联
            Replication,//一个布尔值,该值指示是否使用连接来支持复制
            ConnectTimeout,//在终止尝试并产生错误之前,等待与服务器连接的时间长度(以秒为单位)
            Encrypt,//一个布尔值,该值指示在服务器安装了证书的情况下,SQL Server 是否为客户端和服务器之间发送的所有数据使用 SSL 加密
            TrustServerCertificate,//该值指示在跳过用于验证信任的证书链遍历时是否加密信道
            LoadBalanceTimeout,//连接被销毁前在连接池中存活的最短时间(以秒为单位)
            NetworkLibrary,//一个字符串,该字符串包含用于建立与 SQL Server 的连接的网络库的名称
            PacketSize,//用来与 SQL Server 的实例通信的网络数据包的大小(以字节为单位)
            TypeSystemVersion,//一个字符串值,该值指示应用程序所需的类型系统
            ApplicationName,//与连接字符串关联的应用程序的名称,如果未提供名称,则为“.NET SqlClient Data Provider”
            CurrentLanguage,//获取或设置 SQL Server 语言记录名称
            WorkstationID,//连接到 SQL Server 的工作站的名称
            UserInstance,//该值指示是否将连接从默认的 SQL Server Express 实例重定向到在调用方帐户之下运行并且在运行时启动的实例
            ContextConnection,//该值指示应建立与 SQL Server 的客户端/服务器连接还是进程内连接
            TransactionBinding,//一个字符串值,该值指示该连接如何保持与登记 System.Transactions 事务的关联
            ApplicationIntent,
            MultiSubnetFailover,
            KeywordsCount
        }

通过查看类中初始值,例如MaxPoolSize,MinPoolSize,采用默认值能够满足大多数情况,如果需要特殊处理,只需要修改连接字符串

---------------------------------------------------------------------------------------------------------------------------------------------------------------

那么OleDB,ODBC方式,以及Oracle的连接等,其连接参数如何