String Interpolation in Visual Studio 2015 and IFormatProvider (CA1305)

前端 未结 4 1295
陌清茗
陌清茗 2021-02-02 08:21

The new string interpolation style in Visual Studio 2015 is this:

Dim s = $\"Hello {name}\"

But if I use this the code analysis tells me I brea

4条回答
  •  清歌不尽
    2021-02-02 09:04

    If you're targeting the .NET Framework 4.6, you can take advantage of the fact that string interpolations are implicitly convertible to FormattableString:

    From Customizing string interpolation in C# 6 by Thomas Levesque

    A lesser known aspect of this feature is that an interpolated string can be treated either as a String, or as an IFormattable, depending on the context.

    static string Invariant(FormattableString formattable)
    {
        return formattable.ToString(CultureInfo.InvariantCulture);
    }
    
    string text = Invariant($"{p.Name} was born on {p.DateOfBirth:D}");
    

提交回复
热议问题