我的班级有以下核心:
class SmartDbConnection { private readonly IDbConnection Connection; public SmartDbConnection(string ConnectionString) { if(ConnectionString.Contains("MultipleActiveResultSets=true")) { Connection = new SqlConnection(ConnectionString); } } }
我不希望它有"SqlConnection"硬编码.所以我想把它变成一个Generic类(接受IDbConnection类).但我不知道该怎么做.有人可以帮忙吗?
首先 - 我已经补充说IDisposable
,因为我认为这很重要.
其次,请注意提供商是另一种选择:
class SmartDbConnection { private DbConnection Connection; public SmartDbConnection(string provider, string connectionString) { Connection = DbProviderFactories.GetFactory(provider) .CreateConnection(); Connection.ConnectionString = connectionString; } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } }
如果你必须通用,那怎么样:
class SmartDbConnection: IDisposable where T : class, IDbConnection, new() { private T Connection; public SmartDbConnection(string connectionString) { T t = new T(); t.ConnectionString = connectionString; // etc } public void Dispose() { if (Connection != null) { Connection.Dispose(); Connection = null; } } }
为什么不接受IDbConnection而不是连接到你的ctor?