字符串内插中的可避免拳击 [英] Avoidable boxing in string interpolation

查看:38
本文介绍了字符串内插中的可避免拳击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用字符串插值可使我的字符串格式看起来更加清晰,但是如果我的数据是值类型,则必须添加 .ToString()调用.

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()}";

.ToString()使格式更长且更难看.我试图摆脱它,但是 string.Format 是内置的静态方法,我无法注入它.您对此有什么想法吗?而且由于字符串插值是 string.Format 的语法糖,所以在生成语法糖背后的代码时为什么不添加 .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.

推荐答案

我看不出如何避免编译器进行拳击. string.Format 的行为不是C#规范的一部分.您不能依靠它会调用 Object.ToString().实际上,它不是:

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()}");
    }
}

这篇关于字符串内插中的可避免拳击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆