MSDN 文档包含有关隐式转换的部分:
var s = $"hello, {name}";
System.IFormattable s = $"Hello, {name}";
System.FormattableString s = $"Hello, {name}";
Run Code Online (Sandbox Code Playgroud)
从第一个字符串开始,原始类型的插值字符串就是string.好的,我可以理解它,但是......我意识到字符串没有实现IFormattable.所以它看起来像编译器的一些魔法类似于它对lambdas的作用.
现在猜猜这段代码的输出:
void Main()
{
PrintMe("Hello World");
PrintMe($"{ "Hello World"}");
}
void PrintMe(object message)
{
Console.WriteLine("I am a " + message.GetType().FullName);
}
//void PrintMe(string message)
//{
// Console.WriteLine("I am a string " + message.GetType().FullName);
//}
void PrintMe(IFormattable message)
{
Console.WriteLine("I am a " + message.GetType().FullName);
}
Run Code Online (Sandbox Code Playgroud)
暗示:
我是System.String
我是System.Runtime.CompilerServices.FormattableStringFactory + ConcreteFormattableString
如果您从第二种方法中删除评论,您将获得:
我是一个字符串System.String
我是一个字符串System.String
好的
我可能不太了解重载分辨率,但是C#规范的 14.4.2 …