EDIT:
System.HashCode
.NET Core 中也可用。您可以使用HashCode.Combine
为此,请参阅:https://learn.microsoft.com/en-us/dotnet/api/system.hashcode?view=netcore-2.1 https://learn.microsoft.com/en-us/dotnet/api/system.hashcode?view=netcore-2.1
var combined = HashCode.Combine("one", "two");
(下面是之前的答案)
可以在这里找到长而彻底的答案:https://stackoverflow.com/a/34006336/25338 https://stackoverflow.com/a/34006336/25338
如果您只想要一个简单的答案,您可以将对象哈希组合到一个新的结构(元组、匿名类等)中,然后调用GetHashCode()
关于结果。
e.g.
public override int GetHashCode() {
return new { MyField1, MyField2 }.GetHashCode();
}
详细说明上面链接的答案,如果您想让它更容易(?),您当然可以创建一个通用的静态帮助器类来为您完成工作:
public class MyHashCode
{
public static int Hash(params object[] values)
=> CustomHash(1009, 9176, values.Select(v => v.GetHashCode()).ToArray());
// From answer https://stackoverflow.com/a/34006336/25338
public static int CustomHash(int seed, int factor, params int[] vals)
{
int hash = seed;
foreach (int i in vals)
{
hash = (hash * factor) + i;
}
return hash;
}
}
并这样称呼它:
public class UnitTest1
{
[Fact]
public void Test1()
{
string s1 = "yezz";
string s2 = "nope";
var hash = Utils.MyHashCode.Hash(s1, s2);
}
}