在我们的应用程序中,我们使用具有Guid值的属性创建Xml文件.该值必须在文件升级之间保持一致.因此,即使文件中的其他内容发生更改,该属性的guid值也应保持不变.
一个显而易见的解决方案是创建一个静态字典,其中包含文件名和用于它们的Guids.然后每当我们生成文件时,我们都会在字典中查找文件名并使用相应的guid.但这不可行,因为我们可能会扩展到100个文件并且不想保留大量的guid.
所以另一种方法是根据文件的路径使Guid相同.由于我们的文件路径和应用程序目录结构是唯一的,因此Guid对于该路径应该是唯一的.因此,每次我们运行升级时,文件都会根据其路径获得相同的guid.我找到了一种很酷的方法来产生这样的' 确定性指导 '(感谢Elton Stoneman).它基本上是这样的:
private Guid GetDeterministicGuid(string input)
{
//use MD5 hash to get a 16-byte hash of the string:
MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
byte[] inputBytes = Encoding.Default.GetBytes(input);
byte[] hashBytes = provider.ComputeHash(inputBytes);
//generate a guid from the hash:
Guid hashGuid = new Guid(hashBytes);
return hashGuid;
}
Run Code Online (Sandbox Code Playgroud)
所以给定一个字符串,Guid将始终是相同的.
有没有其他方法或建议的方法来做到这一点?该方法的优点或缺点是什么?
我必须将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服务,必须将数据传递给我无法控制的接口.所以我既不能模拟收到的数据,也不能模拟我必须发送数据的(接口)数据库.另外,我必须以某种方式映射这两个东西,以便我能以某种方式更新项目.叹