C#中的字符串值验证

Posted

技术标签:

【中文标题】C#中的字符串值验证【英文标题】:string value validation in C# 【发布时间】:2011-06-12 01:25:17 【问题描述】:

有两个变量被赋值为“003”和“00 3”。它被转换为 byte[] 如下。

之前:

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

convert()转换后,如果发现有空白字符,则将源字符串转换为字节数组。

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】:

也许可以使用:

        if (ResultVal is byte[]) 
           // SourVal is Invalid;
         else if ( ResultVal is String )  
            //SourVal is valid;
        

【讨论】:

ResultVal is List<byte>。适用于我的情况。谢谢。【参考方案2】:

尝试使用IsWhiteSpace

【讨论】:

IsWhiteSpace 是我从未使用过的好方法。但我可能无法在实践中使用它。我需要处理 ResultVal 作为参数。没有空白了。谢谢。【参考方案3】:
//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


【讨论】:

以上是关于C#中的字符串值验证的主要内容,如果未能解决你的问题,请参考以下文章

c#中的哈希字符串

Veracode 为 C# 中的公共字符串属性引发“技术特定的输入验证问题 (CWE ID 100)”

c#使用线程验证输入字符串并替换为TitleCase

如何在文本文件c#中的字符串已知值之后查找和获取字符串

如何将非统一的 int 范围映射到 C# 中的某些字符串值?

从 C# 中的 JSON 读取特定值