来自 MSDN doc :
public bool Contains(
string value
)
返回值:true 如果 value 参数出现在这个字符串中,或者如果 value 是空字符串 ("");否则,假。
异常:ArgumentNullException : 值 为null。
例子:
string s = string.Empty; //or string s = "";
Console.WriteLine(s.Contains("Hello World!")); //output: False
如果我把它改成:
try
{
string s = null; //or string s;
Console.WriteLine(s.Contains("Hello World!"));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
它会抛出一条错误信息:Object reference not set to an instance of an object
since string
doesn't have a default value (like ""
) 来自 Default Values Table (C# Reference) ,
请回到示例,如果我声明s
,代码将起作用:
string s = "";
现在,对象 s
被设置为一个对象的实例。
所以,我的问题是:MSDN 是否忘记了类似这样的内容:s
cannot be null?
为了检查它,我试过:
string s = null;
Console.WriteLine(!string.IsNullOrEmpty(s) ? s.Contains("Hello World!") : false);
它应该可以工作。
最佳答案
您使用实例更改了值。
myString.Contains(anotherString)
此处 myString
是调用方法 Contains
的实例,而 anotherString
是 value 传递给方法。如果此值为 null
,该方法将抛出 ArgumentNullException
。
另一方面,当将 instance 更改为 null
时,它肯定会导致 NRE,因为您不能在 null 引用上调用任何成员。但是,如果将其设置为 string.empty
Contains
将返回 false
,因为空字符串不包含任何内容(特别是 string.empty
不包含 "Hello World"
,但是 "Hello world"
包含空字符串)。
因此以下返回 false
:
Console.WriteLine(string.Empty.Contains("Hello World"));
虽然这会返回 true
:
Console.WriteLine("Hello World".Contains(string.Empty));
无论如何,您要检查的是空字符串是否包含在任何其他字符串中:
var retVal = myString.Contains(string.empty);
应该返回 true
。
此外 myString.Contains(null)
导致 ArgumentNullException
在另一边 null.Contains(aString)
导致 NRE。
关于c# - 如果默认字符串为空,为什么我不能使用 String.Contains()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954739/