Avoidable boxing in string interpolation

我与影子孤独终老i 提交于 2021-01-27 07:28:00

问题


Using string interpolation makes my string format looks much more clear, however I have to add .ToString() calls if my data is a value type.

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

var person = new Person { Name = "Tom", Age = 10 };
var displayText = $"Name: {person.Name}, Age: {person.Age.ToString()}";

The .ToString() makes the format longer and uglier. I tried to get rid of it, but string.Format is a built-in static method and I can't inject it. Do you have any ideas about this? And since string interpolation is a syntax sugar of string.Format, why don't they add .ToString() calls when generating the code behind the syntax sugar? I think it's doable.


回答1:


I do not see how you can avoid that boxing by compiler. Behavior of string.Format is not part of C# specification. You can not rely on that it will call Object.ToString(). In fact it does not:

using System;
public static class Test {
    public struct ValueType : IFormattable {
        public override string ToString() => "Object.ToString";
        public string ToString(string format, IFormatProvider formatProvider) => "IFormattable.ToString";
    }
    public static void Main() {
        ValueType vt = new ValueType();
        Console.WriteLine($"{vt}");
        Console.WriteLine($"{vt.ToString()}");
    }
}


来源:https://stackoverflow.com/questions/35144363/avoidable-boxing-in-string-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!