我在控制台中跟踪值.两个人相互"对决",我正在使用字典来记录姓名以及损坏.
var duels = new Dictionary<string, string>();
duels.Add("User1", "50");
duels.Add("User2","34");
Run Code Online (Sandbox Code Playgroud)
我正在尝试将两个用户存储在同一个字典行中,因此可以验证User1正在与之对抗User2.这样,如果另一场决斗开始,它就不会干扰User1或User2.
duels.Add("KeyUser1","KeyUser2","50","34",.../*Other attributes of the duel*/);
Run Code Online (Sandbox Code Playgroud)
我需要两把钥匙才能检查用户的损坏位置.损坏总是会转到另一个钥匙 - 反之亦然.我能做些什么来完成这项工作?
谢谢.
您可以尝试为键创建自定义数据类型:
class DualKey<T> : IEquatable<DualKey<T>> where T : IEquatable<T>
{
public T Key0 { get; set; }
public T Key1 { get; set; }
public DualKey(T key0, T key1)
{
Key0 = key0;
Key1 = key1;
}
public override int GetHashCode()
{
return Key0.GetHashCode() ^ Key1.GetHashCode();
}
public bool Equals(DualKey<T> obj)
{
return (this.Key0.Equals(obj.Key0) && this.Key1.Equals(obj.Key1))
|| (this.Key0.Equals(obj.Key1) && this.Key0.Equals(obj.Key0));
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用Dictionary<DualKey<string>, string>;
public class Duel
{
public string User1 {get; protected set;}
public string User2 {get; protected set;}
public Duel(string user1, string user2)
{
User1 = user1;
User2 = user2;
}
public HashSet<string> GetUserSet()
{
HashSet<string> result = new HashSet<string>();
result.Add(this.User1);
result.Add(this.User2);
return result;
}
//TODO ... more impl
}
Run Code Online (Sandbox Code Playgroud)
让我们进行一些决斗。 CreateSetComparer允许字典使用集合的值进行相等测试。
List<Duel> duelSource = GetDuels();
Dictionary<HashSet<string>, Duel> duels =
new Dictionary<HashSet<string>, Duel>(HashSet<string>.CreateSetComparer());
foreach(Duel d in duelSource)
{
duels.Add(d.GetUserSet(), d);
}
Run Code Online (Sandbox Code Playgroud)
并找到决斗:
HashSet<string> key = new HashSet<string>();
key.Add("User1");
key.Add("User2");
Duel myDuel = duels[key];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12527 次 |
| 最近记录: |