Вопрос

CLR languages are expected to understand Unicode, e.g. I can define in C# a function named Δ (Greek Delta). However, when I define such function in IL Asm, the compiler complains about non-ASCII symbols. Is there any solution to this problem?

Это было полезно?

Решение 2

You can write methods containing Unicode characters in IL (compiled with ILAsm) and those methods can be called from C#.

First, the syntax, from §I.5.3 of the CLI spec:

Identifiers are used to name entities. Simple identifiers are equivalent to an ID. However, the ILAsm syntax allows the use of any identifier that can be formed using the Unicode character set. To achieve this, an identifier shall be placed within single quotation marks.

This means the following IL works:

.assembly test {}
.assembly extern mscorlib {}

.class public Delta
{
  .method public static void 'Δ'()
  {
      .entrypoint
      ldstr "Hello, delta!"
      call void [mscorlib]System.Console::WriteLine(string)
      ret
  }
}

The important point though, is that the file has to be saved as UTF-16, otherwise other programs (including the C# compiler) won't recognize the name correctly.

Whit this, you can call the method exactly as you would expect from C#: Delta.Δ().

Другие советы

The method name in the IL will need to be in single quotes. For example, the code:

class Class1
{
   public void \u0394() // Greek Delta
   {
      return;
   }
}

...will compile into:

.method public hidebysig instance void  'Δ'() cil managed
{
  // Code size       4 (0x4)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  br.s       IL_0003
  IL_0003:  ret
} // end of method Class1::'Δ'

Note the single quotes around the method name in the IL above.

Luckily, Visual Studio is smart enough to show the actual Unicode characters which is nice:

enter image description here

Great way to make all your co-workers hate you!

See the Spec for more information.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top