2011-05-25 12 views
0

嗨誰能解釋代碼的這些行,我需要了解它是如何工作才能繼續進行我在做什麼解釋碼

if (e.Error == null){ 
    Stream responseStream = e.Result; 
    StreamReader responseReader = new StreamReader(responseStream); 
    string response = responseReader.ReadToEnd(); 

    string[] split1 = Regex.Split(response, "},{"); 
    List<string> pri1 = new List<string>(split1); 
    pri1.RemoveAt(0); 
    string last = pri1[pri1.Count() - 1]; 
    pri1.Remove(last); 
} 
+1

你不明白哪一行? – 2011-05-25 07:26:06

+0

@Elian這整個塊 – GJJ 2011-05-25 08:43:59

回答

4
// Check if there was no error 
    if (e.Error == null) 
    { 

// Streams are a way to read/write information from/to somewhere 
// without having to manage buffer allocation and such 
     Stream responseStream = e.Result; 

// StreamReader is a class making it easier to read from a stream 
     StreamReader responseReader = new StreamReader(responseStream); 

// read everything that was written to a stream and convert it to a string using 
// the character encoding that was specified for the stream/reader. 
     string response = responseReader.ReadToEnd(); 

// create an array of the string by using "},{" as delimiter 
// string.Split would be more efficient and more straightforward. 
     string[] split1 = Regex.Split(response, "},{"); 

// create a list of the array. Lists makes it easier to work with arrays 
// since you do not have to move elements manually or take care of allocations 
     List<string> pri1 = new List<string>(split1); 
     pri1.RemoveAt(0); 

// get the last item in the array. It would be more efficient to use .Length instead 
// of Count() 
     string last = pri1[pri1.Count() - 1]; 

// remove the last item 
     pri1.Remove(last); 
    } 

我會用一個LinkedList而不是List如果要做的唯一事情就是刪除第一個和最後一個元素。

+0

那麼究竟是什麼split1? – GJJ 2011-05-25 09:36:34

+0

split1是一個字符串數組。如果響應包含「{a},{b},{c}」,您將得到一個帶有「{a」,「b」,「c}」的數組。這使我認爲你想要做'string [] split1 = response.Trim('{','}')。Split(new [] {「},{」},StringSplitOptions.None)'而不是所有行下面,因爲它會給你''a「,」b「,」c「'。 – jgauffin 2011-05-25 09:42:44

+0

不要問什麼'修剪'做什麼。 Google'trim msdn',你會得到答案。 – jgauffin 2011-05-25 09:43:50

0

從我所看到的,它是從一個流讀取可能來自TCP。它讀取整個數據塊,然後使用分隔符},{分隔塊。

因此,如果您有類似abc},{dec的東西,它將被放置到具有2個值的split1數組中,split1 [0] = abc,split1 [1] = dec。

之後,它基本上除去第一和最後一個內容

0

它正在處理錯誤輸出。 它從e收到一個流(我猜這是一個例外),讀它。 它看起來像這樣: 「{DDD},{我失敗},{因爲},{沒有信號} {ENDCODE} 它將它分成不同的字符串,並刪除到第一個和最後一個條目(DDD,ENDCODE )

1

它讀取響應流作爲一個字符串,使該字符串由序列的假設 「{...}」 之間用逗號分開,例如:

{X},{Y},{Z }

然後分裂的字符串 「},{」,給人的

{X

陣列

ý

Z}

然後刪除該數組的第一個元素的第一括號({X => X)和從陣列的最後一個元素的端部支柱(Z} =>ž )。

+0

邏輯上它應該刪除大括號,但從代碼,它似乎並不如此。它似乎是刪除整個{X和Z} – 2011-05-25 07:34:12