C#中的字符串格式操作
一、C#中的字符串内插:$
'KaTeX parse error: Expected 'EOF', got '&' at position 83: …果的字符串表示形式。 &̲ensp; 声明内插…“内插字符串”;内插字符串包含使用{}来插入表达式。
格式:{内插表达式,最小字符数:字符串格式}
string name = "John";
double height = 1.7532;
int age = 24;
//因为在内插字符串中,':'属于特殊字符,所以使用三目运算符时,将':'至于'()'中。
//在内插字符串中使用‘{',使用'}}'。
string message = $"The boy's name is {name}, and he is {age} year{(age == 1 ? "": "s")} old, and he is {height, -10:F2} heigh.(:)}}";
Console.WriteLine(message);
内插表达式的格式控制与对齐方式设定
可通过在内插表达式后添加’:’,设置与具体数据类型支持的对应的显示格式。
{interpolationExpression:format}
通过在内插表达式后添加逗号(“,”)和常数表达式来指定设置了格式的表达式结果的最小字段宽度和对齐方式:
{interpolationExpression,alignment} alignment:<0,左对齐,>0,右对齐。
二、内插字符串的隐式转换
1、转换为当前区域风格(不同地区和国家的显示习惯)的字符串实例;
2、转换为指定区域风格的字符串实例;
3、转换为不变风格的字符串实例;(Invariant).
复合格式字符串(FormattableString):复合格式字符串由固定文本和索引占位符混和组成,其中索引占位符称为格式项,对应于列表中的对象。 格式设置操作产生的结果字符串由原始固定文本和列表中对象的字符串表示形式混和组成。
double speedOfLight = 299792.458;
//复合格式字符串
FormattableString message = $"The speed of light is {speedOfLight} km/s";
//设置当前区域格式为'nl-NL';
System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("nl-NL");
string messageInCurrentCulture = message.ToString();
//获取指定的区域格式并转换
var specificCultre = System.Globalization.CultureInfo.GetCultureInfo("en-IN");
string messageInSpecificCulture = message.ToString(specificCultre);
//设定为不变格式:任何区域的格式转换为统一的格式,便于处理。
string messageInInvariantCultre = FormattableString.Invariant(message);
Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture,-10} {messageInCurrentCulture}");
Console.WriteLine($"{specificCultre,-10}{messageInSpecificCulture}");
Console.WriteLine($"{"Invariant",-10}{messageInInvariantCultre}");
三、@字符作用
1、作为代码元素的前缀,告诉编译器此元素为标识符而非C#关键字;
2、指示原意解释字符串,简单转移序列将按照字面解释,而""则生成一个双引号。若为逐字内插字符串,则{{生成一个大括号。
3、使编译器在命名冲突下区分两种属性;
using System;
using System.Diagnostics;
using System.Transactions;
using Edu;
namespace Edu
{
[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
private string Info;
public InfoAttribute(string info) => Info = info;
}
[AttributeUsage(AttributeTargets.Method)]
public class Info : Attribute
{
private string m_Info;
public Info(string info) => m_Info = info;
}
[InfoAttribute("An example for execute")]
public class program
{//此处@删除后会有对应的错误信息。
[@Info("The main entry point.")]
public static void Main(string[] args)
{
string path1 = "C:\\test\\first.txt";
string path2 = @"\\test\\first.txt";
string greeting = @"John said,""hello""";
string name = "John";
//早期 C# 版本中(8.0之前),$ 标记必须出现在 @ 标记之前。
string test = @$"{name} is a little sad. }}:(";
Console.WriteLine(path1);
Console.WriteLine(path2);
Console.WriteLine(greeting);
Console.WriteLine(test);
}
}
}