是否用布尔值替换()

  • 本文关键字:替换 布尔值 是否 c#
  • 更新时间 :
  • 英文 :


我有一个键值对的Dictionary<string,dynamic>

我还有一个字符串script,其中我需要用字典中的相应值替换所有出现的键。

例如:字典内容:

Param1 : true
Param2 : "False"
Param3 : 123
Param4 : "1234"

String script = " I have Param1 and Param2 and Param3 and Param4 "

现在我想把它转换成

script = " I have true and "False" and 123 and "1234" "

我怎样才能做到这一点?我尝试过script.Replace(),但它不适用于除string之外的数据类型,如果我对其他数据类型使用ToString(),它会大写Boolean值。

编辑:我还浏览了这个链接为什么Boolean.ToString输出"真"而不是";真";。

试试看:

var map = new Dictionary<string, object>()
{
{ "Param1", true },
{ "Param2", "False" },
{ "Param3", 123 },
{ "Param4", "1234" },
};
var script = " I have Param1 and Param2 and Param3 and Param4 ";
var output = map.Aggregate(script,
(s, kvp) => s.Replace(kvp.Key, kvp.Value is string ? $""{kvp.Value}"" : kvp.Value.ToString()));

这相当于:

var output = " I have True and "False" and 123 and "1234" ";

你可能只需要一个。ToLower()在那里。

使用模式"Param\d+"RegularExpressions,您可以将String.Relace()与找到的匹配项一起使用。您必须检查映射中的值是否为bool类型,这样您才能为所需的结果String.ToLower()

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var map = new Dictionary<string, object>()
{
{ "Param1", true },
{ "Param2", ""False"" },
{ "Param3", 123 },
{ "Param4", ""1234"" },
};
var script = " I have Param1 and Param2 and Param3 and Param4 ";
MatchCollection matches = Regex.Matches(script, "Param\d+");
foreach (Match match in matches)
{
object val = map[match.Value];
script = script.Replace(match.Value, val is bool ? val.ToString().ToLower() : val.ToString());
}
Console.WriteLine(script);
}
}

结果:

I have true and "False" and 123 and "1234"

Fiddle演示

您可以通过以下方式完成。

Boolean x = false;
Dictionary<string, dynamic> k = new Dictionary<string, dynamic>();
k.Add("Param1", x.ToString().ToLower());
k.Add("Param2", 123);
Console.WriteLine(string.Format("hi {0} -- {1}", k.Values.ToArray()));

最新更新