GUID 的长度必须为 16 个字节

GUID must be 16 bytes long

我正在尝试使用另一个以字符串作为参数的方法重载一个使用 Guid 作为其参数的方法。

    // read a student object from the dictionary
    static public User Retrieve(Guid ID)
    {
        User user;
        // find the Guid in the Dictionary
        user = Users[ID];
        return user;
    }

    static public User Retrieve(string Email)
    {
        User user;
        Guid id;
        // find the Guid in the Dictionary
        using (SHA1 sha1 = SHA1.Create())
        {
            byte[] hash = SHA1.ComputeHash(Encoding.Default.GetBytes(Email));
            id = new Guid(hash);
        }
        user = Users[id];
        return user;
    }

测试结果 结果信息: 测试方法 SRS.CRUDUsers.UpdateStudent 抛出异常: System.ArgumentException: GUID 的字节数组长度必须恰好为 16 个字节。

测试方法:

    public void UpdateStudent()
    {
        // Arrange
        Student expected = (Student)UserRepo.Retrieve("info@info.com");

        // Act
        Student actual = (Student)UserRepo.Retrieve("info@info.com");
        actual.FirstName = "Joe";
        actual.LastName = "Brown";
        actual.Birthday = new DateTime(1977, 2, 23);
        actual.DegreeSelected = 1;

        // Assert (this is only really checking the object agains itself
        // because both variables are referencing the same object).
        Assert.IsNotNull(actual.ID);
        Console.WriteLine(actual.ID);
        Assert.AreEqual(expected.Name, actual.Name);
        Assert.AreEqual(expected.GetType(), actual.GetType());
        Assert.AreEqual(expected.Birthday, actual.Birthday);
        Assert.AreEqual(expected.Age, actual.Age);
    }

这似乎是一个类型问题,所以很可能是显而易见的。

来自wiki

SHA-1 produces a 160-bit (20-byte)

错误:

Byte array for GUID must be exactly 16 bytes long.

所以你不能只使用 SHA1 作为 Guid。如果这不是与安全相关的代码,您可以尝试 MD5(它是 128)。

尝试关注

new Guid(hash.Take(16).ToArray())

或者您可以使用 MD5 散列,因为它是 16 字节的散列

var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.Default.GetBytes(Email));
new Guid(hash);