【发布时间】:2020-04-30 12:19:59
【问题描述】:
C#中System.Globalization.StringInfo上下文中的文本元素是什么?
我在通过CLR via C#学习C#的过程中,遇到了文本元素的概念。似乎书的读者应该清楚地理解文本元素的全部内容。但我根本不明白这个概念。
另外,the 文档在该主题上并不是很冗长。
我想知道文本元素的定义。
我的猜测是它只是一个 Unicode 字符,没有必要由单个 System.Char 表示(因为在某些情况下它可以由两个 System.Char 表示:高和低代理)。但我不确定我的猜测是否正确。
我的另一个猜测是它是一个完整的单词。
CLR via C#一书中的这段代码中提到了文本元素:
using System;
using System.Text;
using System.Globalization;
using System.Windows.Forms;
public sealed class Program {
public static void Main() {
// The string below contains combining characters
String s = "a\u0304\u0308bc\u0327";
SubstringByTextElements(s);
EnumTextElements(s);
EnumTextElementIndexes(s);
}
private static void SubstringByTextElements(String s) {
String output = String.Empty;
StringInfo si = new StringInfo(s);
for (Int32 element = 0; element < si.LengthInTextElements; element++) {
output += String.Format(
"Text element {0} is '{1}'{2}",
element, si.SubstringByTextElements(element, 1),
Environment.NewLine);
}
MessageBox.Show(output, "Result of SubstringByTextElements");
}
private static void EnumTextElements(String s) {
String output = String.Empty;
TextElementEnumerator charEnum =
StringInfo.GetTextElementEnumerator(s);
while (charEnum.MoveNext()) {
output += String.Format(
"Character at index {0} is '{1}'{2}",
charEnum.ElementIndex, charEnum.GetTextElement(),
Environment.NewLine);
}
MessageBox.Show(output, "Result of GetTextElementEnumerator");
}
private static void EnumTextElementIndexes(String s) {
String output = String.Empty;
Int32[] textElemIndex = StringInfo.ParseCombiningCharacters(s);
for (Int32 i = 0; i < textElemIndex.Length; i++) {
output += String.Format(
"Character {0} starts at index {1}{2}",
i, textElemIndex[i], Environment.NewLine);
}
MessageBox.Show(output, "Result of ParseCombiningCharacters");
}
}
【问题讨论】:
-
在 Remarks 下,它说,".NET 将文本元素定义为显示为单个字符的文本单元,即字形。文本元素可以是基本字符、代理对或组合字符序列。”
-
@madreflection,感谢您提供有关 System.Globalization.StringInfo 的说明。能否请您添加您的最后评论作为答案?另外,请您也提供组合字符序列的定义吗?
-
@GSerg,好文章。谢谢。
-
顺便说一句,这些言论也证实了你对代理对的猜测。