简体   繁体   English

VB6中的Chr转换为C#

[英]Chr from VB6 translated to C#

I'm translating some hardware communication code from VB6 to C#, and got a problem with som communication that need to send chars to the device. 我正在将一些硬件通信代码从VB6转换为C#,但som通信出现了问题,需要将字符发送到设备。 The VB6 Code looks like this: VB6代码如下所示:

Dim STARTQUEST As String
STARTQUEST = Chr(254) + Chr(address + 8) + Chr(address) + Chr(20) + Chr(128) + Chr(3)

And I have done this C# code 我已经完成了此C#代码

String m_startQuest = "";
m_startQuest = m_startQuest + (Char)254 + (Char)(address + 8) + (Char)address + (Char)20 + (Char)128 + (Char)3;

But I get the feel that I don't get the same output from them. 但是我感到我没有从他们那里得到相同的输出。 Atleast in debug the STARTQUEST string looks alot different. 调试STARTQUEST字符串中的STARTQUEST看起来有很大不同。 Is there any other way to get the vb6 function to do the same in C#? 还有什么其他方法可以让vb6函数在C#中执行相同的操作?

One option would be to add a reference to Microsoft.VisualBasic and use the Strings.Chr function 一种选择是添加对Microsoft.VisualBasic的引用并使用Strings.Chr函数

Chr is doing a lot more behind the scenes than you may realize (see the link). Chr在幕后所做的事情比您想像的要多得多(请参阅链接)。

m_startQuest += Encoding.ASCII.GetString(
  new byte[] {254, address + 8, address, 28, 128, 3}
);

Why bytes? 为什么是字节? .Net char type supports Unicode and may be bigger than 255. SO it is safer to use bytes. .Net char类型支持Unicode,并且可能大于255。因此使用字节更安全。

Update: 更新:

A runtime error in VB6 VB6中的运行时错误

Dim s As String
s = Chr(1) + Chr(256)
Debug.Print s

Result is 257 in c#. 结果在c#中为257。

(((char)1) + ((char)256))

Result is a string in c#. 结果是c#中的字符串。

(((char)1) + "" + ((char)256))

a compile time error in c#. C#中的编译时错误。

Encoding.ASCII.GetString(
  new byte[] { 1, 256 }
);

Using the (Char) cast gets you the behaviour of VB6's ChrW (not Chr) function. 使用(Char)强制转换可获取VB6的ChrW(而非Chr)功能的行为。 VB6's Chr function does an ANSI<->Unicode conversion - to duplicate this in C# you can use System.Text.Encoding.Default.GetBytes(). VB6的Chr函数执行ANSI <-> Unicode转换-若要在C#中复制此代码,可以使用System.Text.Encoding.Default.GetBytes()。

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

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