同一账号只写第一次,不同账号第一次爆炸 ,就因为下面部分得到逻辑有问题
修改后的代码如下:1.成功完成角色注册信息的数据库化记录。2.每个账号上限3个角色。3.角色是可以重名的,但是角色的id不会重名。
internal class UserCache
{
private ConcurrentDictionary<string, List<string>> userPlayerIds = dataUserPlayerIds();
//private ConcurrentDictionary<string, List<string>> userPlayerIds = new ConcurrentDictionary<string, List<string>>();
//private ConcurrentDictionary<string, PlayerModel> players = new ConcurrentDictionary<string, PlayerModel>();
private ConcurrentDictionary<string, PlayerModel> players = dataPlayers();//所有账号的角色信息,虽然角色信息中不包含账号id
public static ConcurrentDictionary<string, List<string>> dataUserPlayerIds()//这样好像就行了
{
StreamReader file = new StreamReader("userPlayerIds.txt");
string all = file.ReadToEnd();
file.Close();
ConcurrentDictionary<string, List<string>> results = new ConcurrentDictionary<string, List<string>>();
try
{
//ConcurrentDictionary<string, List<string>> results = JsonConvert.DeserializeObject<ConcurrentDictionary<string, List<string>>>(JsonConvert.DeserializeObject(all).ToString());
results = JsonConvert.DeserializeObject<ConcurrentDictionary<string, List<string>>>(JsonConvert.DeserializeObject(all).ToString());
}
catch {
Console.WriteLine("dataUserPlayerIds()中出现问题");
}
return results;
//return JsonConvert.DeserializeObject(all);
}
public static ConcurrentDictionary<string, PlayerModel> dataPlayers()//这样好像就行了
{
StreamReader file = new StreamReader("players.txt");
string all = file.ReadToEnd();
file.Close();
ConcurrentDictionary<string, PlayerModel> results = new ConcurrentDictionary<string, PlayerModel>();
try
{
results = JsonConvert.DeserializeObject<ConcurrentDictionary<string, PlayerModel>>(JsonConvert.DeserializeObject(all).ToString());
}
catch {
Console.WriteLine("dataPlayers()中出现问题");
}
return results;
//return JsonConvert.DeserializeObject(all);
}
public void put(string accId, PlayerModel model)//逻辑刚开始有些小问题,问题不大
{
bool ur = false;
if (this.userPlayerIds.ContainsKey(accId))//这里出了问题了,同在一个put函数中
{
List<string> stringList;
List<string> stringList_out;
this.userPlayerIds.TryGetValue(accId, out stringList);//得到已有的角色id(player)
stringList.Add(model.id);//给账号新加一个角色
//如果已存账号信息--
//重复的键,TryAdd是家不进去的
ur = this.userPlayerIds.TryRemove(accId, out stringList_out);
ur = this.userPlayerIds.TryAdd(accId, stringList);//同名 键 应该是可以覆盖的--不是第一次先用字符串修改值,再增加到对应键值对中
}
else
{//重来没有,自然不会重复
ur = this.userPlayerIds.TryAdd(accId, new List<string>() { model.id });//第一次只加1个
}
if (ur)//这次应该没问题了
{
StreamWriter file = new StreamWriter("userPlayerIds.txt");
string json = JsonConvert.SerializeObject(this.userPlayerIds);
Console.WriteLine("userPlayerIds.TryAdd:" + json);
file.Write(json);
file.Close();
}
bool pr=this.players.TryAdd(model.id, model);//最后真正怎加角色信息 player=角色 account=账号
//将角色详细信息写入文件
if (pr)
{
StreamWriter file = new StreamWriter("players.txt");
string json = JsonConvert.SerializeObject(this.players);
Console.WriteLine("players.TryAdd:" + json);
file.Write(json);
file.Close();
}
}