[英]Interpolation string from variable c#
I'm trying to interpolate a string combined of two strings in C#. 我试图在C#中内插两个字符串组合而成的字符串。 I have following code in VS 2015:
我在VS 2015中有以下代码:
DateTime date = DateTime.Now;
string username = "abc";
string mask = "{date:yy}/{username}";
What I want in result is: 我想要的结果是:
18/abc
I know that I can interpolate it like: 我知道我可以像这样插值:
mask = $"{date:yy}/{username}"
but mask is also an input. 但是遮罩也是输入。 So i need something like:
所以我需要这样的东西:
string result = $"{mask}"
but the result is : 但结果是:
"{date:yy}/{username}"
Mask is actually downloaded from the database and in each case sequence of information can be different. 掩码实际上是从数据库下载的,在每种情况下,信息序列可能会有所不同。 I need to store in db whole mask and only complement it in code.
我需要将整个掩码存储在db中,并且仅在代码中对其进行补充。 I can't use String.Replace() method like
我不能像这样使用String.Replace()方法
mask.Replace({date}, date.ToString())
because I need to have possibility to add some formatting like :yy, :yyyy, :dd etc. 因为我需要添加诸如:yy,:yyyy,:dd等的格式。
Is there any possibility to do this? 有可能这样做吗?
Sure string.Format()
确定
string.Format()
string mask = string.Format("{0:yy}/{1}", date, username);
or string interpolation 或字符串插值
string mask = $"{date:yy}/{username}";
You can use string.Format()
for that: 您可以为此使用
string.Format()
:
string mask = GetMaskFromDB(); //assume it returns "{0}/{1:yy}"
string username = "abc";
DateTime dt = DateTime.Now;
var result = string.Format(mask, username, dt);
Result: "abc/18"
结果:“ abc / 18”
References: DotNetFiddle Example , String.Format Method 参考: DotNetFiddle示例 , String.Format方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.