首页 > 解决方案 > 在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");
    }
}

标签: c#

解决方案


总之,您颠倒了部分,但您没有更改&&||.


我认为你的问题是关于从

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

在我们的例子中:

  1. A => (x != null)
  2. 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")

推荐阅读