为什么字符串插值宁愿使用string
而不是IFormattable
方法重载?带字符串插值的重载字符串方法
想象一下以下内容:
static class Log {
static void Debug(string message);
static void Debug(IFormattable message);
static bool IsDebugEnabled { get; }
}
我有对象非常昂贵ToString()
。此前,我没有以下内容:
if (Log.IsDebugEnabled) Log.Debug(string.Format("Message {0}", expensiveObject));
现在,我想有IsDebugEnabled逻辑里面Debug(IFormattable)
,并且在消息对象调用toString()只在必要时。
Log.Debug($"Message {expensiveObject}");
但是,这称为Debug(string)
过载。
插值字符串解析字符串' '但隐式类型转换为'IFormattable'。所以,如果你'IFormattable msg = $“Message {expensiveObject}”; Log.Debug(msg);'你应该做生意。请参阅https://msdn.microsoft.com/en-gb/library/dn961160.aspx#Anchor_0 – spender
请参阅[TryRoslyn](http://goo.gl/eiRtVr)上的此示例,IFormattable是烟雾和镜像,带格式()下面:) – PTwr
你应该真的在这里使用'ConditionalAttribute'。 – leppie