相关疑难解决方法(0)

它应该是如此明显,但为什么会失败呢?

多年来一直编码.net我觉得自己像个n00b.为什么以下代码失败?

byte[] a = Guid.NewGuid().ToByteArray(); // 16 bytes in array
string b = new UTF8Encoding().GetString(a);
byte[] c = new UTF8Encoding().GetBytes(b);
Guid d = new Guid(c);    // Throws exception (32 bytes recived from c)
Run Code Online (Sandbox Code Playgroud)

更新

批准了CodeInChaos的答案.可以在他的答案中读取16个字节的原因,即32个字节.答案中也说明了:

UTF8Encoding的默认构造函数已禁用错误检查

恕我直言,当尝试将字节数组编码为包含无效字节的字符串时,UTF8编码器应该抛出异常.为了使.net框架正常运行,代码应该编写如下

 byte[] a = Guid.NewGuid().ToByteArray();
 string b = new UTF8Encoding(false, true).GetString(a);  // Throws exception as expected
 byte[] c = new UTF8Encoding(false, true).GetBytes(b);
 Guid d = new Guid(c);
Run Code Online (Sandbox Code Playgroud)

.net c#

6
推荐指数
1
解决办法
459
查看次数

标签 统计

.net ×1

c# ×1