【问题标题】:Understanding in string concatenation [closed]理解字符串连接[关闭]
【发布时间】:2015-09-22 11:41:53
【问题描述】:

我编写了以下代码,其中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; }
}

提前致谢!!

【问题讨论】:

  • @sstan 所有都是真的。但仍然无法获得所需的输出..
  • @vivek:您必须提供Minimal, Complete, and Verifiable example(强调Complete)才能让我们重现您所看到的内容。正如一个答案所指出的,您发布的代码甚至无法编译。
  • @vivek:就像阿迪尔指出的那样,我得到了Use of unassigned local variable 'Test'。这就是为什么您需要发布一个小而完整的程序来说明您的问题。现在,我们看不到Employee 的定义。我们看不到 3 个变量的设置位置,等等……
  • 您的代码甚至无法编译,请参见:dotnetfiddle.net/Fm9CYs,您的代码无法将"Clear" 作为输出。我投票结束这个问题,因为代码的输出与你在问题中所说的不同。
  • @ekad 。非常感谢您提供该小提琴链接。它对我有很大帮助。现在问题已更新。即使我找到了解决方案。我应该将所有三元运算保留在我错过的第一个三元运算的括号内。您能否发布与答案相同的内容。我也会接受。

标签: c# string string-concatenation


【解决方案1】:

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

    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

    }

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 2018-09-05
    • 1970-01-01
    • 2020-12-18
    • 2012-03-05
    • 2010-09-29
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多