我正在通过套接字发送 bool 值的字符串表示形式并在另一端读取它。
void Send(bool value)
{
Socket.Send(value.ToString());
}
void Receive()
{
string message = Socket.Receive();
Console.WriteLine(message) // Always equal to either 'True' or 'False (without quotes)
bool result = bool.Parse(message) // here I get the format exception.
}
但是当我尝试解析我的消息
时出现以下异常:
String was not recognized as a valid boolean
.
我得到异常时的值是:True
。没有空格。
最佳答案
乍一看,我会认为它有未修剪空间的问题...,但事实并非如此,因为 Boolean.Parse
使用 TryParse
而且,反过来,在其尝试之一中修剪空间:
public static Boolean Parse (String value) {
if (value==null) throw new ArgumentNullException("value");
Contract.EndContractBlock();
Boolean result = false;
if (!TryParse(value, out result)) {
throw new FormatException(Environment.GetResourceString("Format_BadBoolean"));
}
else {
return result;
}
}
public static Boolean TryParse (String value, out Boolean result) {
result = false;
if (value==null) {
return false;
}
// For perf reasons, let's first see if they're equal, then do the
// trim to get rid of white space, and check again.
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
result = true;
return true;
}
if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
result = false;
return true;
}
return false;
}
引用: http://referencesource.microsoft.com/#mscorlib/system/boolean.cs,e2a8f2e50ecf93c0,references
所以,一定有其他事情发生了。格式、UTF-8、ANSI、ASCII 等可能存在问题。您的要求之一是您需要一个 bool 值,这样您就不会出现 True
和 False
,那么为什么不这样做:
bool result = message.ToLower().Contains("true"); // true or false
编辑:
在阅读了一些评论之后,您似乎期待着超出 True
或 False
的情况,在这种情况下,结果可能无效。我建议这样:
var lMessage = message.ToLower();
bool? result = lMessage.Equals("true") ? true : lMessage.Equals("false") ? false : null;
因此,如果消息包含True
,则为true
;如果False
,则为false
;否则为null
,表示无效消息。然后您可以检查 result
是否为 null
并显示无效消息或执行其他操作。我不确定您从那以后的日常事件是什么。
关于c# - 字符串未被识别为有效的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499952/