我必须将Convert Int32转换为Guids,这就是我想出来的.
public static class IntExtensions
{
public static Guid ToGuid(this Int32 value)
{
if (value >= 0) // if value is positive
return new Guid(string.Format("00000000-0000-0000-0000-00{0:0000000000}", value));
else if (value > Int32.MinValue) // if value is negative
return new Guid(string.Format("00000000-0000-0000-0000-01{0:0000000000}", Math.Abs(value)));
else //if (value == Int32.MinValue)
return new Guid("00000000-0000-0000-0000-012147483648"); // Because Abs(-12147483648) generates a stack overflow due to being > 12147483647 (Int32.Max)
}
}
Run Code Online (Sandbox Code Playgroud)
但它有些丑陋.谁有更好的主意?
更新:
是的,我知道整件事情都是丑陋的,但我失去了想法.问题是.我正在获取数据并且必须将其存储到表中我无法更改.发送数据主键是Int,而我必须存储的表主键是Guid.问题是我必须了解发件人正在谈论的对象,但只能将其存储为Guid.
更新2:
好的,我知道我必须在这里提供更多信息.我是一个接收数据的Web服务,必须将数据传递给我无法控制的接口.所以我既不能模拟收到的数据,也不能模拟我必须发送数据的(接口)数据库.另外,我必须以某种方式映射这两个东西,以便我能以某种方式更新项目.叹
Sim*_*ier 59
这是一个简单的方法:
public static Guid ToGuid(int value)
{
byte[] bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
Run Code Online (Sandbox Code Playgroud)
您可以更改复制的位置(将索引从0更改为12).这实际上取决于你想如何定义这种不寻常的"int to Guid"转换.
Yog*_*ise 28
有相同的问题,需要一个Int到Guid然后回到Int.使用int ID的旧数据但处理函数需要Guid.编写额外函数和DB更改的代码很少.更容易以Guid形式传递Int iD,因为它知道它不会使用它作为最终的保存Guid.保存是一个插入,所以它最终得到了一个新的Guid.
Heres是上面的代码和另一个关于Guids to the int并让Int退出的帖子的想法.
public static Guid Int2Guid(int value)
{
byte[] bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
public static int Guid2Int(Guid value)
{
byte[] b = value.ToByteArray();
int bint = BitConverter.ToInt32(b, 0);
return bint;
}
Run Code Online (Sandbox Code Playgroud)
这个Guid2Int只能传递来自Int的Guid.
您可以从int获取数字并对其进行格式化,使它们看起来像GUID,但这不会使结果成为GUID.GUID基本上是一个16字节的数字,使用保证数字唯一的算法计算.您可以在世界上的每台计算机上整天生成GUID,而不是重复(至少这是理论上的).重新格式化的int不是唯一的,它绝对不是GUID.