好吧,我只是不知道如何做到这一点,还是这种方法存在根本问题?
给定以下所需的公共API:
[Fact]
public void GroupManagerCanAddNewGroupWithConnectionId()
{
var groupName = "ThisNewGroup";
var connectionId = "ThisNewConnection";
var sut = new GroupManager();
sut.Add(groupName, connectionId);
Assert.Contains(groupName, sut.Groups);
Assert.Contains(connectionId, sut.Groups[groupName]);
}
我如何实现以下内容,这显然是不合法的,因为它没有编译:
private readonly ConcurrentDictionary<string, HashSet<string>> groups =
new ConcurrentDictionary<string, HashSet<string>>();
public IEnumerable<string> Groups { get { return this.groups.Keys; } }
public IEnumerable<string> Groups[string i] { get { return this.groups[i]; } }
public void Add(string groupName, string connectionSring)
{
groups.AddOrUpdate(
groupName,
new HashSet<string>(new string[1] { connectionSring }),
(conn, list) => { list.Add(conn); return list; });
}
使用类中的索引器通过密钥访问字典
public IEnumerable<string> this[string key]
{
get
{
return groups[key];
}
}
我知道这是可以做到的。我添加了一个包装类来管理访问,然后通过继承IEnumerable并提供属性索引器来定义访问。然后,我的团队经理课程变得简单了。现在我的测试通过了。
public class GroupManager
{
private readonly GroupStore groups = new GroupStore();
public GroupStore Groups { get { return this.groups; } }
public void Add(string groupName, string connectionSring)
{
groups.Add(groupName, connectionSring);
}
}
public class GroupStore : IEnumerable<string>
{
private readonly ConcurrentDictionary<string, HashSet<string>> groupStore = new ConcurrentDictionary<string, HashSet<string>>();
public IEnumerable<string> this[string index] { get { return this.groupStore[index]; } }
public IEnumerator<string> GetEnumerator()
{
return groupStore.Keys.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
public void Add(string groupName, string connectionSring)
{
//groupStore.AddOrUpdate(...);
}
}