问题
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