2013-08-27 125 views
1

我不是VB6-ish人。我只需要將一些代碼從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的字符串,我需要對它進行解碼。非常感謝你!

+0

爲什麼二進制數據在字符串中? –

回答

2
Comm_ReceiveData = Comm_ReceiveData.Substring(1); 

應該這樣做。 Substring有一個單參數版本,只需要子字符串的開始位置。

+0

當我使用這段代碼時,我會得到「1BP215009010137 \ r」嗎?謝謝 –

+0

@CaressCastañares是的。 – FrankPl

2

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的回答有子串更有意義,使用的變種。

0

Mid $通過返回最好的子字符串或通過返回源字符串來優雅地處理出界錯誤。

該方法從VB6中爲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; 
}