是否有“ String.Format”?可以接受命名输入参数而不是索引占位符? [英] Is there a "String.Format" that can accept named input parameters instead of index placeholders?

查看:108
本文介绍了是否有“ String.Format”?可以接受命名输入参数而不是索引占位符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所知道的

str = String.Format("Her name is {0} and she's {1} years old", "Lisa", "10");

但是我想要类似的东西

str = String("Her name is @name and she's @age years old");
str.addParameter(@name, "Lisa");
str.addParameter(@age, 10);


推荐答案

在C#6中,您可以使用字符串插值

In C# 6 you can use string interpolation:

string name = "Lisa";
int age = 20;
string str = $"Her name is {name} and she's {age} years old";






Doug Clutter -can-accept-named-input-parameters-instead-of-ind / 36759931#comment61134257_36759806>他的评论,字符串插值还支持格式字符串。可以通过在冒号后面指定格式来更改格式。下面的示例将输出一个带有逗号和两位小数位的数字:


As Doug Clutter mentioned in his comment, string interpolation also supports format string. It's possible to change the format by specifying it after a colon. The following example will output a number with a comma and 2 decimal places:

var str = $"Your account balance is {balance:N2}"






他的答案中提到的 https://stackoverflow.com/users/668272/bas\">Bas ,字符串插值不支持模板字符串。实际上,它对此没有内置支持。幸运的是,它存在于一些很棒的库中。


As Bas mentioned in his answer, string interpolation doesn't support template string. Actually, it has no built in support for that. Fortunately it exists in some great libraries.

SmartFormat.NET 例如支持命名占位符:

SmartFormat.NET for example has support for named placeholder:

Smart.Format("{Name} from {Address.City}, {Address.State}", user)

// The user object should at least be like that 

public class User
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
    public string State { get; set; }
}

可以在 NuGet

胡子 也是一个很好的解决方案。 Bas 他的答案

这篇关于是否有“ String.Format”?可以接受命名输入参数而不是索引占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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