为什么字符串插值偏好使用带有
想象以下情景:
现在,我想要在
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));
现在,我希望在Debug(IFormattable)
内部有IsDebugEnabled逻辑,并且仅在必要时对消息中的对象调用ToString()。现在,我想要在
Debug(IFormattable)
函数内加入IsDebugEnabled逻辑,仅在必要时才对消息中的对象调用ToString()。Log.Debug($"Message {expensiveObject}");
然而,这调用了Debug(string)
重载。
string
,但具有对IFormattable
的隐式类型转换。因此,如果您使用IFormattable msg = $"Message {expensiveObject}"; Log.Debug(msg);
,则应该可以正常工作。请参见 https://msdn.microsoft.com/en-gb/library/dn961160.aspx#Anchor_0 - spenderConditionalAttribute
。 - leppie