代码之家  ›  专栏  ›  技术社区  ›  Daan

可以在格式字符串中包含条件检查代码吗?

  •  1
  • Daan  · 技术社区  · 16 年前

    我有一个自定义控件,它是列表的一部分。它应该显示的文本是通过为其文本属性赋值来设置的。在运行时,此文本从数据库加载。我想在本文前面加上字符串“toelichting:”(荷兰语表示“说明”)。我可以通过将控件的FormatString属性设置为以下值来完成此操作:

    "Toelichting: {0}"
    

    现在,如果加载的文本是空字符串,我想显示“toelichting:–”,所以在末尾加一个短划线。否则,我想显示“toelichting:mytext”。是否可以向FormatString添加一些条件检查代码,以便检查参数是否不为空?

    4 回复  |  直到 16 年前
        1
  •  1
  •   John Saunders    16 年前

    不,没有办法。

        2
  •  5
  •   David M    16 年前

    为什么不只是这个?

    string.Format("Toelichting: {0}", string.IsNullOrEmpty(explanation) ? "–" : explanation);
    

    我认为没有办法把它嵌入到格式字符串中。

        3
  •  1
  •   Andrew Hare    16 年前

    你可以这样做:

    String.Format("Toelichting: {0}", 
        (String.IsNullOrEmpty(yourstr)) ? "-" : yourstr);
    

    不完美,但相对紧凑,可读。

        4
  •  1
  •   Community CDub    8 年前

    如果你经常做这种事情,那么考虑编写你自己的格式化程序,这样你就可以编写这样的代码…

    foo=string.format(new myformatter(),“toelichting:0:解释”,bar);

    MyFormatter将实现IFormatProvider和ICustomFormatter。

    看看这个…

    .NET: Is there a String.Format form for inserting the value of an object property into a string?

    …这可能比您需要的要复杂(因为它处理反射和处理任何对象)