带条件的IF条件

时间:2011-08-24 09:54:56

标签: c# .net windows string if-statement

快一点:

string firstline; 
if (firstline == null) {
    System.Console.WriteLine("String empty!");
}

理论上如果“firstline”中没有值,控制台应该输出“String empty!”?

7 个答案:

答案 0 :(得分:6)

由于以下原因甚至无法编译:

  

使用未分配的局部变量'firstline'

当你说你没有得到任何输出但程序编译并且运行得很好时,你没有向我们展示你的真实代码。


但是,如果firstline不是局部变量而是周围类的成员变量,则它将使用null自动初始化。通常,类的所有成员变量都使用default(T)进行初始化,其中T是成员变量的类型。

答案 1 :(得分:1)

你无法在VS中编译错误:使用未分配的局部变量'firstline'!

尝试在之前指定null!

修改

class Program
{
    static string firstline; # with static you can compile and got your behaviour

    static void Main(string[] args)
    {


        if (firstline == null)
        {
            System.Console.WriteLine("String empty!");
        }

        Console.ReadKey();
    }
}

答案 2 :(得分:1)

默认情况下,它们不为空。如果你想在默认情况下为null,请使用:

static string firstline;
static void Main(string[] args)
{

    if (firstline == null)
    {
        System.Console.WriteLine("String empty!");
    }
}

但我建议使用这个:

static void Main(string[] args)
{
    string firstline = null;
    // or this:
    //string firstline = String.Empty;
    if (String.IsNullOrEmpty(firstline))
    {
        System.Console.WriteLine("String empty!");
    }
}

在这两种方式中你都可以获得

之谜
  

使用未分配的局部变量'firstline'

答案 3 :(得分:0)

是的,它会按照您的预期运行,并应打印到控制台。如果您没有以下代码,您可能会发现控制台应用程序关闭得太快,无法读取结果。

同样为null和“”(或String.Empty)通常意味着相同的事情,因此更多的命令方式是:

if(String.IsNullOrEmpty(firstline))
{
   Console.WriteLine("String is empty!");
}

答案 4 :(得分:0)

您的代码不正确,使用未分配的本地变量'firstline'。您可以为其分配任何值以进行测试。如果要检查它是否为空字符串,更好的方法是:

string firstline = null;  //change to "" to test
if (string.IsNullOrEmpty(firstline))
{
  System.Console.WriteLine("String empty!");
}

答案 5 :(得分:0)

你的术语听起来有点像你有点困惑。

null字符串恰恰就是 - 缺少值。它不是一个空字符串,它是一个没有值的字符串。

空字符串是零长度字符串,""string.Empty。这不是null,因为它有一个值,但该值为零长度。

通常,您希望将null值和空值视为相同,在这种情况下,您可以使用检查

if (string.IsNullOrEmpty(firstline))
{
    System.Console.WriteLine("String is null or empty!");
}

答案 6 :(得分:0)

这是我的2美分:

 if (firstline == (string)null) throw new ArgumentNullException("firstline"); //value is null
 if (firstline.Length == 0) throw new ArgumentOutOfRangeException("firstline", "Value is empty"); // string.Empty

我使用Pex and Moles

找到了这个