用nullables连接多个字符串

时间:2014-07-21 16:27:19

标签: c#

我有一个消息框,用于在数据库中显示一些文本和数据(如果存在)。当前问题试图显示空值并尝试转换为ShortDate。我采取了两种方法,但没有一种方法可以按照我需要的方式工作。

第一种方法在字符串中使用三元连接,但它表现得非常奇怪。

DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
                            + "\n Existing Client:  " + DuplicateName.Forename + " " + DuplicateName.Surname
                            + "\n Date of Birth:  " +  DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",  
                            ,"Possible Duplicate Client", MessageBoxButtons.YesNo);

目前,消息框仅显示换行符和出生日期。甚至没有文字“出生日期”

如果我删除第三和转换,只需

DialogResult DuplicateMessage = MessageBox.Show("A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
                            + "\n Existing Client:  " + DuplicateName.Forename + " " + DuplicateName.Surname
                            + "\n Date of Birth:  " +  DuplicateName.DOB
                            ,"Possible Duplicate Client", MessageBoxButtons.YesNo);

这有效,可以显示一切。唯一的问题是出生日期格式错误。想知道如何制作它,所以日期是短日期格式,并将显示所有内容。

'DuplicateName'的所有属性都可以为空,

2 个答案:

答案 0 :(得分:2)

我怀疑这是使用条件运算符的运算符优先级的问题。它可能包括字符串连接作为被测试条件的一部分,而不是作为结果的一部分。您可以使用括号明确地包含该运算符的元素,以标识哪些字符串属于哪些字符串,哪些字符串不属于:

"\n Date of Birth:  " +  (DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ")

此外,如果DOBDateTime?,那么您可以稍微简化一下代码:

"\n Date of Birth:  " +  (DuplicateName.DOB.HasValue ? DuplicateName.DOB.Value.ToString("yyyy-mm-dd") : " ")

无需在Convert类型上使用Nullable<T>,您可以更轻松(并且安全地)使用HasValueValue属性。

答案 1 :(得分:1)

您可以使用另一对括号来修复它:

(DuplicateName.DOB != null ? Convert.ToDateTime(DuplicateName.DOB))

在第一种情况下,您将一个巨大的字符串连接在一起(因为您不使用任何括号),然后对null进行测试。它等同于:

var stringToTest = "A contact name " + DuplicateName.Forename + " " + DuplicateName.Surname + " already exists within the System."
                        + "\n Existing Client:  " + DuplicateName.Forename + " " + DuplicateName.Surname
                        + "\n Date of Birth:  " +  DuplicateName.DOB;


DialogResult DuplicateMessage =
    MessageBox.Show(stringToTest != null ? Convert.ToDateTime(DuplicateName.DOB).ToString("yyyy-mm-dd") : " ",  
                    ,"Possible Duplicate Client", MessageBoxButtons.YesNo);
相关问题