C#中的字符串插补可变格式

编程入门 行业动态 更新时间:2024-10-23 00:26:30
本文介绍了C#中的字符串插补可变格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要格式化字符串插一个变量,格式字符串是另一个变量:

I need to format a variable with string interpolation, and the format string is another variable:

下面是我的示例代码:

static void Main(string[] args) { int i = 12345; Console.WriteLine($"Test 1: {i:N5}"); var formatString = "N5"; Console.WriteLine($"Test 2: {i:formatString}"); }

1的测试工作,测试2不工作。

Test 1 works, Test 2 don't work.

什么是用于测试2的确切语法

What's the exact syntax for Test 2 ?

推荐答案

您的代码等同于:

Your code is equivalent to:

Console.WriteLine(String.Format("Test 2: {0:formatString}", i));

由于的formatString 是格式字符串,你要嵌套的String.Format 要求把数值格式字符串:

As the formatString is in the format string, you would nest String.Format calls to put the value in the format string:

Console.WriteLine(String.Format(String.Format("Test 2: {{0:{0}}}", formatstring), i));

这是不支持用绳子插值。

This isn't supported with string interpolation.

更多推荐

C#中的字符串插补可变格式

本文发布于:2023-11-08 14:05:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   格式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!