C# string 和 list contains 使用注意事项
string 使用contains
string testStr = string.Empty;
//此时调用contains 判断是否含有字符串 是没问题的,result 为false
var result = testStr.Contains("test");
//此时调用contains 判断是否含有字符 也是没问题的,result 为false
result = testStr.Contains('t');
//如果把testStr 置为null, 判断字符或者字符串都有问题,
testStr = null;
result = testStr.Contains("test");
result = testStr.Contains('t');
//都会抛Object reference not set to an instance of an object
string 在用contains 判断字符或字符串时 需要对string 对象做判空操作,string.IsNullOrWhiteSpace
//判空
if(string.IsNullOrWhiteSpace(testStr ))
{
}
list 使用contains
//对List, 使用Contains 判断是否含有某个元素
var strList = new List<string>();
strList.Add("test");
//使用contains 判断,result为true
result = strList.Contains("test");
//如果把strList 置为null,再去判断均会抛空引用异常
strList = null;
result = strList.Contains("test1");
//会抛Object reference not set to an instance of an object
list 在使用contains 时,需要对list 进行判空,
// 判空
if(strList == null || !strList .Any())
{
}