问题描述
我要转换转换的Int32成的GUID,这就是我想出了。
I have to convert Convert Int32 into Guids and this is what I came up with.
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)
}
}
但它在某种程度上难看。有没有人一个更好的主意?
谢谢你很多
But it’s somehow ugly. Has anybody a better idea?Thank you a lot.
更新:
是的,我知道整个事情是丑陋的,但我想法的损失。
的问题是。我得到的数据,并有将其存储到一个表我不能改变。发送数据主键是一个int和表pimary关键我要存储它是一个GUID。
的问题是我要了解哪个对象发送者在谈论,但只能将其存储为一个GUID
Yes I know the whole thing is ugly but I am a loss of Ideas.The problem is. I am getting data and have to store it into a Table I cannot change. The sending data primary key is a Int and the table pimary key I have to store it is a Guid.The problem is I have to understand what object the sender is talking about but can only store it as a Guid.
更新2:
好吧,我知道我必须在这里提供更多信息。我是一个web服务接收数据和ahve沿着数据传递到接口我也无法控制。所以,我既不可以模拟在那里我有发送数据接收的数据也不是(接口)的数据库。 Additionaly我不知怎么得的方式映射这两个东西,所以我不知可以更新项目。的叹息的
Okay I see I have to provide more info here. I am a Webservice receiving data and ahve to pass along data to an Interface I also can not control. So I neither can model the data received nor the (Interface)database where I have to send the data. Additionaly I have somehow have to map these two thing in a way so I somehow can update a item. sigh
推荐答案
下面是一个简单的方法来做到这一点:
Here is a simple way to do it:
public static Guid ToGuid(int value)
{
byte[] bytes = new byte[16];
BitConverter.GetBytes(value).CopyTo(bytes, 0);
return new Guid(bytes);
}
您可以更改副本会发生(变化从0到12的指数)。这真的取决于你想如何定义这个不寻常的int值的Guid的转换。
You can change where the copy will happen (vary the index from 0 to 12). It really depends on how you want to define this unusual "int to Guid" conversion.
这篇关于转换的int的Guid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!