C#中有符号整数与无符号整数之间的二进制值拷贝

因为我现在需要将uint作为字典的键进行存储,这就需要编写一个GetHashCode(),那么最好的办法就是直接把它的二进制值拷贝为1个int

这里给出我的intuint之间的直接拷贝方法:

int x;
uint y;
y = BitConverter.ToUInt32(BitConverter.GetBytes(x), 0);
x = BitConverter.ToInt32(BitConverter.GetBytes(y), 0);

那么GetHashCode()就长这样了:

using System;
public interface IIdUsingUInt32
{
	Int32 id { get; set; }  // 为了适配数据库的命名风格,并避免命名转换,这里直接使用下划线命名法。

	public class EqualityComparer : IEqualityComparer<IIdUsingUInt32>
	{
		public bool Equals(IIdUsingUInt32 x, IIdUsingUInt32 y) => x.id == y.id;

		public int GetHashCode(IIdUsingUInt32 obj) => BitConverter.ToInt32(BitConverter.GetBytes(obj.id), 0);
	}
}