使用 C# 10.0?只需使用字符串插值处理程序
Custom String Interpolation Handlers are documented here 和 here
(我还没有任何 C# 10.0 功能的经验,但我会在未来扩展这部分 - 现在我仍然困在 C# 7.3 领域 -job 的项目对 .NET Framework 4.8 的依赖)
使用 C# 1.0 到 C# 9.0?
快速修复:Boolean 包装结构
如果您控制字符串格式调用站点,则只需更改 bool/Boolean-typed 值以使用可隐式转换的零开销值类型,例如:
public readonly struct YesNoBoolean : IEquatable<YesNoBoolean>
{
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators
public static implicit operator Boolean ( YesNoBoolean self ) => self.Value;
public static implicit operator YesNoBoolean( Boolean value ) => new MyBoolean( value );
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/true-false-operators
public static Boolean operator true( YesNoBoolean self ) => self.Value == true;
public static Boolean operator false( YesNoBoolean self ) => self.Value == false;
public YesNoBoolean( Boolean value )
{
this.Value = value;
}
public readonly Boolean Value;
public override String ToString()
{
return this.Value ? "Yes" : "No";
}
// TODO: Override Equals, GetHashCode, IEquatable<YesNoBoolean>.Equals, etc.
}
所以您的示例调用站点变为:
double d = Math.PI;
DateTime now = DateTime.Now;
YesNoBoolean isPartyTime = true; // <-- Yay for implicit conversion.
string result = $"{d:0.0}, {now:HH:mm}, time to party? {isPartyTime}";
而result 将是"3.1, 21:03, time to party? Yes"
冒泡:不,你不能覆盖Boolean.TrueString 和FalseString
因为Boolean 的static readonly String TrueString = "True"; 也标有initonly,所以不能使用反射覆盖它,所以这样做:
typeof(Boolean).GetField( "TrueString" )!.SetValue( obj: null, value: "Yes" );
...会给你一个运行时异常:
在类型 'System.Boolean' 初始化后无法设置 initonly static field 'TrueString'。
仍然可以通过操作原始内存,但这超出了这个问题的范围。
使用IFormatProvider 和ICustomFormatter:
始终可以通过提供自定义IFormatProvider 来覆盖String.Format 和插值字符串(例如$"Hello, {world}")的格式;虽然String.Format 通过暴露Format 重载参数使其变得容易,但内插字符串不会,而是迫使您丑化您的代码。
- 在 .NET 中实现
IFormatProvider(仍然)出人意料地不足。
- 要记住的主要事情是
IFormatProvider.GetFormat(Type) 只使用以下 3 个 formatType 参数之一调用:
typeof(DateTimeFormatInfo)
typeof(NumberFormatInfo)
typeof(ICustomFormatter)
- 在整个 .NET BCL 中,没有其他
typeof() 类型被传递到 GetFormat(至少 ILSpy 和 RedGate Reflector 告诉我)。
魔法发生在ICustomFormatter.Format 内部,实现起来很简单:
public class MyCustomFormatProvider : IFormatProvider
{
public static readonly MyCustomFormatProvider Instance = new MyCustomFormatProvider();
public Object? GetFormat( Type? formatType )
{
if( formatType == typeof(ICustomFormatter) )
{
return MyCustomFormatter.Instance;
}
return null;
}
}
public class MyCustomFormatter : ICustomFormatter
{
public static readonly MyCustomFormatter Instance = new MyCustomFormatter();
public String? Format( String? format, Object? arg, IFormatProvider? formatProvider )
{
// * `format` is the "aaa" in "{0:aaa}"
// * `arg` is the single value
// * `formatProvider` will always be the parent instance of `MyCustomFormatProvider` and can be ignored.
if( arg is Boolean b )
{
return b ? "Yes" : "No";
}
return null; // Returning null will cause .NET's composite-string-formatting code to fall-back to test `(arg as IFormattable)?.ToString(format)` and if that fails, then just `arg.ToString()`.
}
public static MyFormat( this String format, params Object?[] args )
{
return String.Format( Instance, format: format, arg: args );
}
}
...所以只需以某种方式将MyCustomFormatProvider.Instance 传递给String.Format,如下所示。
double d = Math.PI;
DateTime now = DateTime.Now;
bool isPartyTime = true;
string result1 = String.Format( MyCustomFormatProvider.Instance, "{0:0.0}, {1:HH:mm}, time to party? {2}", d, now, isPartyTime );
// or add `using static MyCustomFormatProvider` and use `MyFormat` directly:
string result2 = MyFormat( "{0:0.0}, {1:HH:mm}, time to party? {2}", d, now, isPartyTime );
// or as an extension method:
string result3 = "{0:0.0} {1:HH:mm}, time to party? {2}".MyFormat( d, now, isPartyTime );
// Assert( result1 == result2 == result3 );
所以这适用于String.Format,但是我们如何将MyCustomFormatProvider 与C# $"" 插值字符串一起使用...?
...非常困难,因为设计插值字符串功能的 C# 语言团队使其总是通过provider: null,所以所有值都使用它们的默认值(通常特定于文化的)格式,并且它们没有提供任何轻松指定自定义 IFormatProvider 的方法,即使有几十年前的静态代码分析 rule against relying on implicit use of CurrentCulture(尽管 Microsoft打破自己的规则...)。
- 很遗憾,覆盖
CultureInfo.CurrentCulture 将不起作用,因为 Boolean.ToString() 根本不使用 CultureInfo。
困难在于 C# $"" 插值字符串 are always implicitly converted to String(即立即格式化)除非 $"" 字符串表达式直接分配给类型化的变量或参数就像FormattableString 或IFormattable,但真气 this does not extend to extension methods (so public static String MyFormat( this FormattableString fs, ... ) won't work。
唯一这里可以做的事情是调用 String MyFormat( this FormattableString fs, ... ) 方法作为(语法上“正常”)静态方法调用,尽管使用 using static MyFormattableStringExtensions 在某种程度上减少了人体工程学问题 -如果您使用 global-usings(这需要 C# 10.0,它已经支持自定义插值字符串处理程序,所以这有点没有实际意义)更是如此。
但是像这样:
public static class MyFormattableStringExtensions
{
// The `this` modifier is unnecessary, but I'm retaining it just-in-case it's eventually supported.
public static String MyFmt( this FormattableString fs )
{
return fs.ToString( MyCustomFormatProvider.Instance );
}
}
并像这样使用:
using static MyFormattableStringExtensions;
// ...
double d = Math.PI;
DateTime now = DateTime.Now;
bool isPartyTime = true;
string result = MyFmt( $"{d:0.0}, {now:HH:mm}, time to party? {isPartyTime}" );
Assert.AreEqual( result, "3.1, 23:05, time to party? Yes" );
或者只是改变FormattableString的参数数组
- 似乎除了在函数调用中包装内插字符串(如上面的
MyFmt( $"" ))之外别无选择,有一个更简单的替代方法来实现IFormatProvider 和ICustomFormatter:只需编辑FormattableString's直接值参数数组。
- 因为这种方法要简单得多,如果您还不需要在
String.Format(IFormatProvider, String format, ...) 中格式化 Boolean 值,则更可取。
- 像这样:
public static class MyFormattableStringExtensions
{
public static String MyFmt( this FormattableString fs )
{
if( fs.ArgumentCount == 0 ) return fs.Format;
Object?[] args = fs.GetArguments();
for( Int32 i = 0; i < args.Length; i++ )
{
if( args[i] is Boolean b )
{
args[i] = b ? "Yes" : "No";
}
}
return String.Format( CultureInfo.CurrentCulture, fs.Format, arg: args );
}
}
并像以前一样使用以获得相同的结果:
using static MyFormattableStringExtensions;
// ...
double d = Math.PI;
DateTime now = DateTime.Now;
bool isPartyTime = true;
string result = MyFmt( $"{d:0.0}, {now:HH:mm}, time to party? {isPartyTime}" );
Assert.AreEqual( result, "3.1, 23:05, time to party? Yes" );