如何从多个密钥创建缓存密钥?

Eli*_*son 4 caching

我有一个方法,其输出我将缓存.它需要四个参数; string,string,int,和WindowsIdentity.我需要根据这四个参数创建一个缓存键.最好是:

将它们作为字符串连接在一起并使用该键?

var key = string.Concat(string1, string2, int1.ToString(), identity.ToString());
Run Code Online (Sandbox Code Playgroud)

要么

他们的哈希码是什么?

var key = string1.GetHashCode() ^ string2.GetHashCode() ^ int1.GetHashCode() ^ identity.GetHashCode();
Run Code Online (Sandbox Code Playgroud)

或者是其他东西?有关系吗?在我的特定情况下,这些键只会进入Hashtable(C#v1).

Jon*_*eet 8

创建一个封装四个值的新类型.例如:

public sealed class User
{
    private readonly string name;
    private readonly string login;
    private readonly int points;
    private readonly WindowsIdentity identity;

    public User(string name, string login, int points,
                WindowsIdentity identity)
    {
        this.name = name;
        this.login = login;
        this.points = points;
        this.identity = identity;
    }

    public string Name { get { return name; } }
    public string Login { get { return login; } }
    public int Points { get { return points; } }
    public WindowsIdentity Identity { get { return identity; } }

    public override bool Equals(object other)
    {
        User otherUser = other as User;
        if (otherUser == null)
        {
            return false;
        }
        return name == otherUser.name &&
               login == otherUser.login &&
               points == otherUser.points &&
               identity.Equals(otherUser.identity);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 31 + name.GetHashCode();
        hash = hash * 31 + login.GetHashCode();
        hash = hash * 31 + points.GetHashCode();
        hash = hash * 31 + identity.GetHashCode();
        return hash;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这假定WindowsIdentity覆盖EqualsGetHashCode适当 - 或者您对引用类型相等感到满意.

这种方法比你的任何一个建议都强大得多 - 例如,在你的第一种方法中,两个字符串对"xy","z"和"x","yz"最终会形成相同的缓存键(如果int和identity是相同的)而他们不应该.第二种方法可能导致意外的哈希冲突.