在C#中,一个字符串变量中的两个双引号实际上代表什么?

3

我最近遇到一个问题,让我想知道在C#中两个双引号对编译器有什么意义。

string Var, blankVar;

Var = null; //Var is not instantiated or defined.
Var = ""; //Var should be blank or empty, but it is not null.
Var = "house"; //Var is defined as the string value house.
blankVar = ""; //blankVar should be blank or empty, but it is not null.

此时,编译器应该已经将“house”这个值存储到字符串变量Var中。字符串变量blankVar应该为空。
if (Var.Contains(blankVar)) //if "house" contains "" then..
{
// do something
}

如果变量Var等于“house”且不为空(“”),为什么编译器仍然会进入if语句?
1个回答

4
每个字符串都包含空字符串。从逻辑上讲,这是有道理的,因为每个字符串都包含长度为零的某些子字符串,包括空字符串本身。
Contains方法只是反映了这一点。请参见文档
返回值: 类型: System.Boolean 如果value参数出现在该字符串中或者value是空字符串(""),则为true;否则为false。

甚至可以说文档中陈述的都是显而易见的(当然,除了提问者……)。 - Jongware
@Jongware 是的,这可能不是每个人都能理解的。我记得当我第一次了解到空集时,它是每个其他集合(包括它自己)的子集时,我感到惊讶。当时这让我很吃惊(尽管经过一段时间的思考后,我意识到它必须是这样的)。 - p.s.w.g

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接