gpt4 book ai didi

C#:属性与常量的不同字符串编码

转载 作者:行者123 更新时间:2023-12-03 16:31:58 26 4
gpt4 key购买 nike

我正在为一个旨在删除无效代码点(例如孤立代理对)的函数编写测试。
但是,根据我编写测试的方式,我发现代理对的编码方式有所不同。
虽然此版本的测试通过:

        [TestCategory("UnitTest")]
[TestMethod]
public void RemoveOrhpanedSurrogatePair()
{
var input = "\uDDDD1975";
var cleanText = input.ReplaceInvalidCodePoints();

Assert.AreEqual(input.Length - 1, cleanText.Length);
Assert.AreEqual("1975", cleanText);
}
这个没有:
        [TestCategory("UnitTest")]
[TestMethod]
[DataRow("\uDDDD1975")]
public void RemoveOrhpanedSurrogatePair(string input)
{
var cleanText = input.ReplaceInvalidCodePoints();

Assert.AreEqual(input.Length - 1, cleanText.Length);
Assert.AreEqual("1975", cleanText);
}
查看调试器,第一个变体将字符串编码为 "\uDDDD1975"但第二个产生 "��1975"它显示为两个有效字符,而不是一对孤立的代理项。

最佳答案

我认为答案的线索可以在(除了)@jonskeet blog post 中找到。 .显然,C# 在任何地方都使用 UTF16 来编码字符串,除了在使用 UTF8 的属性 c'tors 中。编译器似乎看到这是一个孤立的代理对,并通过其 UTF8 值将其视为两个无效的 Unicode 字符。然后这些被一对 \uFFFD 取代字符(Unicode replacement character,用于在将二进制解码为文本时指示损坏的数据)。

[Description(Value)]
class Test
{
const string Value = "\uDDDD";

static void Main()
{
var description = (DescriptionAttribute)
typeof(Test).GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
DumpString("Attribute", description.Description);
DumpString("Constant", Value);
}

static void DumpString(string name, string text)
{
var utf16 = text.Select(c => ((uint) c).ToString("x4"));
Console.WriteLine("{0}: {1}", name, string.Join(" ", utf16));
}
}
将产生:
Attribute: fffd fffd
Constant: dddd

关于C#:属性与常量的不同字符串编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65516309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com