简体   繁体   English

编码问题:将vbscript“ Chr()”转换为.Net C#

[英]Encoding issue: vbscript “Chr()” to .Net C#

I can't seem to find the answer to this question. 我似乎找不到这个问题的答案。

It seems like I should be able to go from a number to a character in C# by simply doing something along the lines of (char)MyInt to duplicate the behaviour of vb's Chr() function; 似乎我应该能够通过简单地沿(char)MyInt的代码做一些事情来复制vb的Chr()函数的行为,从而将C#中的数字转换为字符。 however, this is not the case: 然而,这种情况并非如此:

In VB Script w/ an asp page, if my code says this: 在带有asp页面的VB脚本中,如果我的代码表明:

Response.Write(Chr(139))

It outputs this: 它输出:

‹ (character code 8249)

Opposed to this: 反对:

(character code 139) (字符代码139)

I'm missing something somewhere with the encoding, but I can't find it. 我在编码中缺少某些地方,但是找不到。 What encoding is Chr() using? Chr()使用什么编码?

Chr() uses the system default encoding, I believe - so it's roughly equivalent to: 我相信Chr()使用系统默认编码-因此大致相当于:

byte[] bytes = new byte[] { 139 };
char c = Encoding.Default.GetString(bytes)[0];

On my box (Windows CP1252 as the default) that does indeed give Unicode 8249. 在我的机器上(默认为Windows CP1252)确实提供了Unicode 8249。

If you want to call something that has exactly the behaviour of VB's Chr from C#, then, why not simply call it rather than trying to deduce its behaviour? 如果您想从C#调用具有VB的Chr完全相同行为的东西,那么,为什么不简单地调用它而不是尝试推断其行为呢?

Just put a "using Microsoft.VisualBasic;" 只需输入一个“使用Microsoft.VisualBasic;” at the top of your C# program, add the VB runtime DLL to your references, and go to town. 在C#程序的顶部,将VB运行时DLL添加到您的引用中,然后转到城镇。

If you cast an int to a char , you will get the character with the Unicode character code that was in the integer. 如果将int转换为char ,则将获得具有整数形式的Unicode字符代码的字符。 The char data type is just a 16 bit UTF-16 character code. char数据类型只是一个16位UTF-16字符代码。

To get the equivalent of the VBScript chr() function in .NET you would need something like: 要获得.NET中的VBScript chr()函数的等效功能,您将需要以下内容:

string s = Encoding.Default.GetString(new byte[]{ 139 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM