gpt4 book ai didi

c# - 带字符串插值的重载字符串方法

转载 作者:可可西里 更新时间:2023-11-01 09:00:06 28 4
gpt4 key购买 nike

为什么字符串插值更喜欢使用 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()。

Log.Debug($"Message {expensiveObject}");

但是,这会调用 Debug(string) 重载。

最佳答案

这是一个 deliberate decision by the Roslyn team :

We generally believe that libraries will mostly be written with different API names for methods which do different things. Therefore overload resolution differences between FormattableString and String don't matter, so string might as well win. Therefore we should stick with the simple principle that an interpolated string is a string. End of story.

链接中对此有更多讨论,但结果是他们希望您使用不同的方法名称。

Some library APIs really want consumers to use FormattableString because it is safer or faster. The API that takes string and the API that takes FormattableString actually do different things and hence shouldn't be overloaded on the same name.

关于c# - 带字符串插值的重载字符串方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770713/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com