2011-06-12 61 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 

}