如何创建唯一的键值?

10 c#

我有两个班级之间的关系Credentials<=>UserData.我想MemoryCache用来过滤我的传入请求.

key = Credentialvalue = UserData.

(Data)MemoryCache.Default.AddOrGetExisting(GetKey(credential), // must be a string
                                           userData,
                                           DateTime.Now.AddMinutes(5));
Run Code Online (Sandbox Code Playgroud)

如何实现public string GetKey(Credentials credential)传入请求?

CredentialsDataContract包含其他DataContracts类似的GoogleCredentials,FacebookCredentials.它们包含了自己的strings喜欢user_namepassword.

现在,缓存项添加了键credential.ToString(),此方法对于Credentials具有相同凭据值的对象返回相同的值,对具有Credentials不同凭据值的实例返回不同的值,这一点很重要.

在Credential类中,我有以下方法

public override int GetHashCode()
{
    int hashCode = 0;

    if (GoogleCredentials!= null)
    {
        hashCode ^= GoogleCredentials.GetHashCode();
    }

    if (FacebookCredentials!= null)
    {
        hashCode ^= FacebookCredentials.GetHashCode();
    }

    return hashCode;
}
Run Code Online (Sandbox Code Playgroud)

Vad*_*nov 3

这是一个关于数据和对象唯一性的问题。.NET 中有一种比较两个对象的机制。它使用EqualsGetHashCode方法。EqualityComparer还有另一种基于相同机制的方法。

GetHashCode 返回您的对象的唯一整数代码。您可以为您的凭证类重写此方法,或创建工作原理类似的外部方法,然后调用 ToString() 以获得唯一代码。有很多 指南如何以正确的方式实现 GetHashCode 。实际的实现将取决于您的对象结构。