string内插是指用$"日期:{DateTime.Now.ToString("yyyy年MM月dd日")}。",这种使用方式,在c#10.0时,引进了这种string内插的处理,可以写自定义的处理程序,来提升使用体验。具体用法见下面的代码:

/// <summary>
/// string内插处理类型
/// </summary>
[InterpolatedStringHandler]
public ref struct TestInterpolatedStringHandler
{
/// <summary>
/// 构建字符串的stringbuilder
/// </summary>
StringBuilder builder;
/// <summary>
/// 两个长度是必需的
/// </summary>
/// <param name="literalLength"></param>
/// <param name="formattedCount"></param>
public TestInterpolatedStringHandler(int literalLength, int formattedCount)
{
builder = new StringBuilder(literalLength);
}

/// <summary>
/// 添加非格式化部分,如果被 {}分隔,会调用多次
/// </summary>
/// <param name="s"></param>
public void AppendLiteral(string s)
{
builder.Append(s);
}
/// <summary>
/// 添加格式化部分,如果有多个{},会调用多次
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void AppendFormatted<T>(T t)
{
builder.Append(t?.ToString());
}
internal string GetFormattedText() => builder.ToString();
}

  那这个自定义的内插处理程序有什么用呢?我们举个实际的例子吧,如果把处理程序带入参数,就能用效的来控制ApppendLiteral和AppendFormatted了。

  通过传入角色role,来决定AppendFormatted时,用正常的内容,或是用脱敏的******,这样一来,就把判断处理工作交给了内插处理程序了,当然这只是很少的一块,可以根据role类型,进行不同权限层次的脱敏,从而形成了一个自定义内插脱敏的模块。具体代码如下:

using static System.Console;
using System.Runtime.CompilerServices;
using System.Text;

var name = "张三";
var total = 10000.0m;
var result = TestParameter("admin", $"本次向 {name} 转账:{total} 元");
WriteLine(result);

result = TestParameter("viewer", $"本次向 {name} 转账:{total} 元");
WriteLine(result);

static string TestParameter(string role, [InterpolatedStringHandlerArgument("role")] ParameterInterpolatedStringHandler handler)
{
return handler.GetFormattedText();
}

[InterpolatedStringHandler]
public ref struct ParameterInterpolatedStringHandler
{
/// <summary>
/// 构建字符串的stringbuilder
/// </summary>
StringBuilder builder;

string _role;
/// <summary>
/// 两个长度是必需的
/// </summary>
/// <param name="literalLength"></param>
/// <param name="formattedCount"></param>

public ParameterInterpolatedStringHandler(int literalLength, int formattedCount, string role)
{
_role = role;
builder = new StringBuilder(literalLength);
}

/// <summary>
/// 添加非格式化部分,如果被 {}分隔,会调用多次
/// </summary>
/// <param name="s"></param>
public void AppendLiteral(string s)
{
builder.Append(s);
}
/// <summary>
/// 添加格式化部分,如果有多个{},会调用多次
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void AppendFormatted<T>(T t)
{
if (_role.ToLower() == "admin")
{
builder.Append(t?.ToString());
}
else
{
builder.Append("******");
}
}
internal string GetFormattedText() => builder.ToString();
}

  想要更快更方便的了解相关知识,可以关注微信公众号 

c#10:string内插处理_字符串