我在这里有个问题。
我正在获取看起来像这样的字符串:“简单文本:{1},日期:{3}”->从数据库中获取 我想用employee.Name替换“ {1}”,用Date.Now替换“ {3}”。 用我从数据库中知道的替换哪个数字,有很多不同的类型,因此我需要动态地执行此操作,因此字符串替换应如下所示:
String.Replace("{someNumber}", extract from the database but it is a string but should be property like emplayee.Name).
我不知道该怎么做,因为函数将“ emplayee.Name”而不是“ John”(即employeeName)放入
这里是一个示例:
content = content.Replace(match.ToString(), emailVariableDictionary[ExtractIdFromMatch(match.ToString())].Variable);
emailVariableDictionary是一个列表,其中包含诸如“ employee.Name,Date.Now”之类的字符串,并且像String.Format之前的“ emplyee.Name”而不是“ John”之前所说的那样
答案 0 :(得分:0)
var template = "simple text : {0}, and date : {1}";
var replacedString = string.Format(template, "John",DateTime.Now);
如果我使用您的“简单文本:{1}和日期:{3}”,则字符串格式基于索引,您可以使用以下格式
var template = "simple text : {1}, and date : {3}";
var replacedString = string.Format(template,"index 0", "John","index 2",DateTime.Now);
答案 1 :(得分:0)
请使用字符串插值概念。它在下面的链接中可用
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
示例:
string name = "Mark";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.