2011-06-12 59 views
0

有兩個變量被賦值爲「003」和「00 3」。它被轉換爲byte []如下。C#中的字符串值驗證

之前:

myStr1 = "003"; // valid, there is no blank inserted. 
myStr2 = "00 3"; // invalid, there is one blank character or multi blanks character inserted. 

轉換通過轉換(後),如果有發現空白字符,源串將轉換爲字節數組。

myVal1 = "3"; // valid after convert 
myVal2[0] = 0; // invalid, since the source myStr2 is invalid. 
myVal2[1] = 1; // same as above. 

現在我需要根據轉換的結果確定源字符串是有效的還是無效的。我不知道如何說結果是一個字節數組。請給我一些建議。提前致謝。

輸入字符串類型的輸出電流值爲SourVal

if (ResultVal is Byte Array) // how to translate the statement to C# code? 
    SourVal is Invalid; 
else if (ResultVal is still String type) // how to translate the statement to C# code? 
    SourVal is valid; 

PS:我沒有在我的實踐嘗試的typeof()和將gettype()的方法。我不知道如何使用這些方法。或者還有其他更好的方法用於我的驗證。

+1

吧?請更清楚。 – kenny 2011-06-12 01:27:57

+0

你能展示更多的代碼並更好地解釋你正在努力完成的任務嗎?你的轉換功能會有幫助。 – 2011-06-12 01:41:14

回答

1

也許還可以利用:

 if (ResultVal is byte[]) { 
      // SourVal is Invalid; 
     } else if (ResultVal is String) { 
      //SourVal is valid; 
     } 
+0

'ResultVal是List '。適用於我的案例。謝謝。 – 2011-06-12 08:16:41

1

嘗試使用IsWhiteSpace

+0

'IsWhiteSpace'是我從未使用過的好方法。但我也許不能在我的練習中使用它。我需要處理'ResultVal'作爲參數。沒有白色空間了。謝謝。 – 2011-06-12 01:42:31

1
//Check the String for Blank spaces if found then don't convert 

if(!str.Contains(" ")) 

{ 

//use the convert method 

} 
else 

{ 

//Write Message for an Invalid String 

}