C#插值字符串中的可选参数是什么? [英] What is the optional argument in C# interpolated string for?

查看:92
本文介绍了C#插值字符串中的可选参数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

插值字符串是C#6.0的新功能之一。

Interpolated strings is one of the new features of C# 6.0.

根据MSDN,嵌入式C#表达式的语法可以包含可选的逗号分隔值,称为< optional-逗号- 文档中的字段宽度

According to MSDN, the syntax of the embedded C# expressions can contain an optional, comma-separated value, deemed as <optional-comma-field-width> in the documentation.

很遗憾,我没有找到此字段的用途。

Unfortunately I didn't find what this field is for.

从名称上可能会认为此值设置了内插字段的最大大小,但是当我尝试以下表达式时:

From its name one might think that this value sets the maximal size of the "interpolated" field, but when I try the following expression:

var p = Process.GetCurrentProcess();
Console.WriteLine($"Process name is {p.ProcessName, 5}");

我得到以下输出:

Process name is LINQPad.UserQuery


推荐答案

这是用于该字段的最小宽度,而不是最大。由于您的字符串长于您为宽度指定的5个字符,因此该字段将扩展为您的字符串的长度。宽度越大,您会看到的差异越明显:

It's the minimum width to use for that field, not the maximum. Since your string is longer than the 5 characters you specify for the width, the field is extended to the length of your string. You'll see the difference more dramatically with a longer width:

var p = Process.GetCurrentProcess();
$"Process name is {p.ProcessName, 50}".Dump();

收益率:

Process name is                                  LINQPad.UserQuery

正字段大小是右对齐的;负字段大小左对齐。

A positive field size is right-justified; a negative field size is left-justified.

文档在 MSDN的复合格式页:


可选的对齐方式组件是带符号的整数,表示
首选格式化字段的宽度。如果alignment的值比格式化的字符串的长度小
,则忽略对齐,并将格式化的字符串的
长度用作字段宽度。如果对齐方式为正
,则字段中的
格式数据将右对齐,如果对齐方式为负,则将数据左对齐。如果需要填充,则使用
空格。如果指定了对齐方式,则必须使用逗号。

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

这篇关于C#插值字符串中的可选参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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