如何让这个类的通用? (.NET C#) [英] How to make this class generic? (.NET C#)
本文介绍了如何让这个类的通用? (.NET C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的类有以下核心:
类SmartDbConnection
{
私人只读的IDbConnection连接;
公共SmartDbConnection(字符串的ConnectionString)
{
如果(ConnectionString.Contains(MultipleActiveResultSets =真))
{
连接=新的SqlConnection(ConnectionString的);
}
}
}
我不希望它有的SqlConnection硬codeD。因此,我认为在使其成为一个通用类(接受的IDbConnection类)。但我不知道该怎么做。任何人都可以帮忙吗?
解决方案
首先 - 我已经添加了的IDisposable
来这一点,因为我认为这是非常重要的。
二,请注意提供者是一个替代的位置:
类SmartDbConnection
{
私人的DbConnection连接;
公共SmartDbConnection(字符串提供商,字符串的connectionString)
{
连接= DbProviderFactories.GetFactory(供应商)
.CreateConnection();
Connection.ConnectionString =的connectionString;
}
公共无效的Dispose(){
如果(连接!= NULL)
{
Connection.Dispose();
连接= NULL;
}
}
}
如果你必须去一般,怎么样:
类SmartDbConnection< T> :IDisposable的其中T:类,
的IDbConnection,新的()
{
私人T连接;
公共SmartDbConnection(字符串的connectionString)
{
T(T)=新T();
t.ConnectionString =的connectionString;
// 等等
}
公共无效的Dispose(){
如果(连接!= NULL)
{
Connection.Dispose();
连接= NULL;
}
}
}
My class has the following core:
class SmartDbConnection
{
private readonly IDbConnection Connection;
public SmartDbConnection(string ConnectionString)
{
if(ConnectionString.Contains("MultipleActiveResultSets=true"))
{
Connection = new SqlConnection(ConnectionString);
}
}
}
I don't want it to have "SqlConnection" hardcoded. So I thought in making it a Generic class (accepting IDbConnection classes). But I don't know how to do it. Anyone can help?
解决方案
First - I've added IDisposable
to this, as I believe it is important.
Second, note that providers are an alternative here:
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;
}
}
}
If you must go generic, how about:
class SmartDbConnection<T> : 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;
}
}
}
这篇关于如何让这个类的通用? (.NET C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文