c# - 在c#中检查字符串是否为空而不会出错
问题描述
在第 3 行我得到空异常。“描述”是一个字符串,有时值为空。在它进入 - (!Discription.ToLower().StartsWith("da") 并抛出错误之前我可以做些什么检查?或者我如何让空值可以接受?
private void FindBook(a, b)
{
if (discription == null && (!Discription.ToLower().StartsWith("da"))) //getting 'Can't be NULL' exception here.How do approach this issue? How do I fix this?
{
IsInLibrary = false;
}
else
{
IsInLibrary = true;
}
}
public string Discription
{
get
{
return _discription;
}
set
{
_discription = value;
if (value != null && (value.ToLower().StartsWith("da"))) //it is working here
{
IsInLibrary = true;
}
OnPropertyChanged("Discription");
}
}
解决方案
总之,您颠倒了部分,但您没有更改&&
为||
.
我认为你的问题是关于从
if (x != null && x.ToLower().StartsWith("da"))
{
y = true;
}
至
if (???)
{
y = false;
}
选项 A. 全部反转
你可以实现它!围绕 if 的全部内容:
if (!(x != null && x.Something()))
{
y = false;
}
选项 B. 德摩根定律
德摩根定律可以表示为
not (A or B) = not A and not B
not (A and B) = not A or not B.
我们要使用第二定律:
not (A and B) = not A or not B
在我们的例子中:
A => (x != null)
B => (x.ToLower().StartsWith("da"))
然后:
不是 ((x != null)
和(x.ToLower().StartsWith("da"))
)
等于
不(x != null)
_(x.ToLower().StartsWith("da")
这可以简化为:
x == null
或者!x.ToLower().StartsWith("da")
在 C# 中:
x == null || !x.ToLower().StartsWith("da")
推荐阅读
- laravel - 在没有模型的情况下将数据插入迁移
- ajax - Laravel 如果 id 存在则更新记录
- arrays - 给定Google表格中的一系列行,计算最大的单日总和
- git - 使用 git ssh 访问构建 Docker 容器,加载密钥“/root/.ssh/id_rsa”:格式无效
- python - 如何编写一个打印三个数字中最大数字的函数
- javascript - 计算所有数字之和的 Javascript 函数(使用更快的运行时性能)
- javascript - 如何旋转相机/世界以专注于任何实体
- java - 为什么 ObjectAnimator 在不同的手机/设备之间有不同的速度?
- python - python list of list 常见元素迭代
- java - 如何使用Apache POI从excel(xlsx)文件中读取整数单元格值作为字符串而不进行任何更改