我在使用.NET Reflector查看mscorelib.dll时,发现了Char类。我一直想知道像Char.isLetter这样的方法是如何实现的。我预期会有一个巨大的测试列表,但是通过深入挖掘,我发现了一个非常简短的代码来确定Unicode类别。然而,这段代码使用了某种表格和一些位移操作。有人可以解释一下这是如何实现的,或者给我指点一些资源吗?
编辑:这里是代码。它在System.Globalization.CharUnicodeInfo中。
编辑:这里是代码。它在System.Globalization.CharUnicodeInfo中。
internal static unsafe byte InternalGetCategoryValue(int ch, int offset)
{
ushort num = s_pCategoryLevel1Index[ch >> 8];
num = s_pCategoryLevel1Index[num + ((ch >> 4) & 15)];
byte* numPtr = (byte*) (s_pCategoryLevel1Index + num);
byte num2 = numPtr[ch & 15];
return s_pCategoriesValue[(num2 * 2) + offset];
}
s_pCategoryLevel1Index
是一个 short*
类型的变量,而 s_pCategoryValues
则是一个 byte*
类型的变量。
这两个变量都是在 CharUnicodeInfo 的静态构造函数中创建的:
static unsafe CharUnicodeInfo()
{
s_pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr(typeof(CharUnicodeInfo).Assembly, "charinfo.nlp");
UnicodeDataHeader* headerPtr = (UnicodeDataHeader*) s_pDataTable;
s_pCategoryLevel1Index = (ushort*) (s_pDataTable + headerPtr->OffsetToCategoriesIndex);
s_pCategoriesValue = s_pDataTable + ((byte*) headerPtr->OffsetToCategoriesValue);
s_pNumericLevel1Index = (ushort*) (s_pDataTable + headerPtr->OffsetToNumbericIndex);
s_pNumericValues = s_pDataTable + ((byte*) headerPtr->OffsetToNumbericValue);
s_pDigitValues = (DigitValues*) (s_pDataTable + headerPtr->OffsetToDigitValue);
nativeInitTable(s_pDataTable);
}
这里是UnicodeDataHeader。
internal struct UnicodeDataHeader
{
// Fields
[FieldOffset(40)]
internal uint OffsetToCategoriesIndex;
[FieldOffset(0x2c)]
internal uint OffsetToCategoriesValue;
[FieldOffset(0x34)]
internal uint OffsetToDigitValue;
[FieldOffset(0x30)]
internal uint OffsetToNumbericIndex;
[FieldOffset(0x38)]
internal uint OffsetToNumbericValue;
[FieldOffset(0)]
internal char TableName;
[FieldOffset(0x20)]
internal ushort version;
}
注意:我希望这不会违反任何许可证。如果有违规,我将删除代码。