【发布时间】:2012-03-01 12:07:59
【问题描述】:
所有,我有一个需要定期附加和分离多个 SQL 数据库的应用程序。我想创建一个类,将所有这些数据库保存为可以迭代的集合。为此,我继承自 ICollection,但有些想法我不理解:
class SqlDataBases : ICollection<SqlDb>
{
private List<SqlDb> dbColl;
public SqlDataBases()
{
dbColl = new List<SqlDb>();
}
// Add an index to the collection.
public SqlDb this[int _nIndex]
{
get { return (SqlDb)dbColl[_nIndex]; }
set { dbColl[_nIndex] = value; }
}
// et al.
}
public class DbEnumerator : IEnumerator<SqlDb>
{
// ...
}
class SqlDb
{
private string strMdfFullPath;
private string strLdfFullPath;
private bool bIsAttached;
public SqlDb(string _strMdfFullPath, string _strLdfFullPath, bool _bIsAttached)
{
this.strMdfFullPath = _strMdfFullPath;
this.strLdfFullPath = _strLdfFullPath;
this.bIsAttached = _bIsAttached;
}
}
我的问题是“为什么要从 ICollection 继承,当您必须自己添加诸如 'Add'、'Contains' 等方法时?或者您是否必须按照MSDN 中的建议自己执行此操作?我一直在阅读“C# in a Nutshell”,这个问题在这本好书中没有得到解决。
我很抱歉,我知道我在这里遗漏了一些东西......
【问题讨论】:
-
我的想法是一样的;你为什么不在需要的地方使用
List<SqlDb>?据我所知,它具有您尝试实现的功能。 -
@Killercam,下面的一条评论建议使用字典。除非您想一遍又一遍地按名称“查找”您的连接,否则 Dictionary 会更好,因为您可以指定数据库名称之类的键。
标签: c# icollection