if(String.IsNullOrEmpty(myString))和if(String.IsNullOrWhitespace(myString))仍然用于空字符串

时间:2018-03-02 00:32:16

标签: c# if-statement

我的目标是通过服务器从其他客户端获取消息并处理该消息。服务器和其他客户端是visual basic,如果我尝试在两个vb客户端之间进行通信,一切都很好,但我需要c#中的客户端用于我的Unityproject。 我的问题是控制台上仍然有空消息,所以我认为if()不能正常工作。 以下是本准则的相关部分:

try
            {
                theStream = mySocket.GetStream();
                Byte[] inStream = new Byte[mySocket.SendBufferSize];
                theStream.Read(inStream, 0, inStream.Length);
                serverMsg += Encoding.ASCII.GetString(inStream);
                serverMsg = serverMsg.Trim();

                //if ((serverMsg == null || serverMsg == "")) doesn't work
                //if (String.IsNullOrWhiteSpace(serverMsg)) doesn't work
                //if (String.IsNullOrEmpty(serverMsg) || serverMsg.Length <1) doesn't work  
                INOWS = false;
                INOWS = IsNullOrWhiteSpace(serverMsg);

                if (INOWS) 
                {
                    // do nothing
                }
                else
                {
                    Debug.Log("[SERVER] -> " + serverMsg);

                }
            }
            catch (Exception e)
            {
                Debug.Log("[Fehler]" + e);
            }
        } while (socketReady == true);
public static bool IsNullOrWhiteSpace(string value)
{
    if (value != null)
    {
        for (int i = 0; i < value.Length; i++)
        {
            if (!char.IsWhiteSpace(value[i]))
            {
                return false;
            }
        }
    }
    return true;
}

感谢您提示我尝试使用IsNullOrWhiteSpace,但这给了我一个错误"'string' does not contain a definition for IsNullOrWhiteSpace" 所以我使用this IsNullOrWhitespace但是我仍然在控制台上为每个korrekt字符串至少获得一个空字符串。 console view你对我有其他任何暗示吗?

2 个答案:

答案 0 :(得分:1)

if (String.IsNullOrWhitespace(serverMsg))                    
                {
                    // do nothing
                }

IsNullOrWhitespace()检查null,空白(“”)和空(“”)

答案 1 :(得分:-1)

尝试修剪字符串:如果字符串中包含任何空白字符,它仍将无法通过IsNullOrEmpty()测试。

在这种情况下(特别是用户或网络服务输入),我通常会使用类似

的内容
List.exists f
相关问题