查看: 76|回复: 0

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

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-10-3
发表于 2025-7-22 11:04:00 | 显示全部楼层 |阅读模式

因为我现在需要将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);
	}
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部