在字符串连接中理解

时间:2015-07-05 03:57:43

标签: c# string string-concatenation

我编写了以下代码,其中IsClearIsPermanentIsSalaried为真。 IsSalaried是一个可以为空的布尔值。我期待像"Clear,Permanent,Salaried"这样的输出。但它仅将输出设为"Clear"。任何人都可以帮助我理解以下概念:

using System;

public class Program
{
    public static void Main()
    {
        MyClass Employee = new MyClass();
        Employee.IsClear = true;
        Employee.IsPermanent = true;
        Employee.IsSalaried = true;

        string Test =  
             Employee.IsClear ? "Clear" : ""
            + (Employee.IsPermanent ? "Permanent" : "") 
            + (Employee.IsSalaried.HasValue ? "Salaried" : "");

        Console.WriteLine(Test);
    }
}

public class MyClass
{
    public bool IsClear { get; set; }
    public bool IsPermanent { get; set; }
    public bool? IsSalaried { get; set; }
}

提前致谢!!

1 个答案:

答案 0 :(得分:1)

这应该会产生编译错误,因为Test在右侧未初始化!以下应该有效:

    static void Main(string[] args)
    {
        bool a = true;
        bool b = true;
        bool c = true;
        string x = "";
        string Test = x + (a ? "Clear" : "") + (b ? "Permanent" : "") + (c ? "Salaried" : "");
        Console.WriteLine(Test);

        Console.ReadLine(); //so that my console window doesn't close

    }