【问题标题】:Mid$ function translate from VB6 to C#Mid$ 函数从 VB6 转换为 C#
【发布时间】:2013-08-27 23:16:30
【问题描述】:

我不是一个 VB6 的人。我只需要为我们的项目将一些代码从 VB6 翻译成 C#。 我在 VB6 上有这段代码

Comm_ReceiveData = Mid$(Comm_ReceiveData, 2, Len(Comm_ReceiveData))

此代码位于Timer1_Timer() 子函数中。

我将此行转换为 C#

Comm_ReceiveData = Comm_ReceiveData.Substring(1, Comm_ReceiveData.Length);

所以在 C# 中,我收到了这个错误。

Index and length must refer to a location within the string.

字符串 Comm_ReceiveData 是“01BP215009010137\r”。我相信长度是 17

是的,我知道我会在 C# 中遇到这种错误。我想知道为什么我在 VB6 上没有出错。 是否有另一种方法可以将该 VB6 代码转换为 C#? VB6 代码对“越界”错误不敏感吗?

顺便说一句,我正在使用该代码进行串行通信。我从我的 arduino 中得到一个字符串到 C#/VB6,我需要对其进行解码。非常感谢!

【问题讨论】:

  • 为什么二进制数据在字符串中?

标签: c# timer vb6 serial-port


【解决方案1】:

Mid$ 函数最多返回指定的长度。如果字符数少于长度,则返回(无错误)从开始位置到字符串结尾的字符。您显示的 VB6 代码相当草率地依赖于 Mid$ 的特定行为,并且是不必要的,因为如果 Mid$ 完全省略了长度参数,它们的行为将相同。本页说明:http://www.thevbprogrammer.com/Ch04/04-08-StringFunctions.htm

所以 C# 中的文字等价物是

Comm_ReceiveData = Comm_ReceiveData.Substring(1, Comm_ReceiveData.Length-1);

但 FrankPl 的答案具有更有意义的 Substring 变体。

【讨论】:

    【解决方案2】:
    Comm_ReceiveData = Comm_ReceiveData.Substring(1);
    

    应该可以解决问题。 Substring 有一个单参数版本,只需要子字符串的起始位置。

    【讨论】:

    • @Caress Castañares 是的。
    【解决方案3】:

    Mid$ 通过返回尽可能好的子字符串或返回源字符串来优雅地处理越界错误。

    此方法再现了 VB6 for C# 中 Mid$ 函数的行为。

    /// <summary>
    /// Function that allows for substring regardless of length of source string (behaves like VB6 Mid$ function)
    /// </summary>
    /// <param name="s">String that will be substringed</param>
    /// <param name="start">start index (0 based)</param>
    /// <param name="length">length of desired substring</param>
    /// <returns>Substring if valid, otherwise returns original string</returns>
    public static string Mid(string s, int start, int length)
    {
        if (start > s.Length || start < 0)
        {
            return s;
        }
    
        if (start + length > s.Length)
        {
            length = s.Length - start;
        }
    
        string ret = s.Substring(start, length);
        return ret;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      相关资源
      最近更新 更多