Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用字典进行字符串插值_C#_.net_String - Fatal编程技术网

C# 如何使用字典进行字符串插值

C# 如何使用字典进行字符串插值,c#,.net,string,C#,.net,String,我有一个带有键值对的字典,我需要使用字符串插值,然后根据命名参数映射字符串。请帮帮我 // code removed for brevity var rawmessage = "Hello my name is {Name}"; // raw message var dict= new Dictionary<string, object>(); dict.Add("{Name}", response.Name); 到目前为止,我找到了解决方案: var message =

我有一个带有
键值对的字典
,我需要使用字符串插值,然后根据命名参数映射字符串。请帮帮我

// code removed for brevity
var rawmessage = "Hello my name is {Name}"; // raw message
var dict= new Dictionary<string, object>();
dict.Add("{Name}", response.Name);
到目前为止,我找到了解决方案:

     var message = parameters.Aggregate(message, 
(current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString()));
它工作得很好,但我的经理真的希望我在字典中使用字符串插值。我不知道如何做到这一点。请引导我

它工作得很好,但我的经理真的希望我在字典中使用字符串插值。我不知道如何做到这一点

你不能那样做。C#插值字符串不是模板引擎,而是编译时功能,它转换为
string.Format
调用。这就是为什么不能在常量表达式中使用字符串插值

我想使用字符串插值将命名参数(作为键出现在字典中)映射到它们各自的值。但我不想使用String.Replace。有什么出路吗

实际上,您可以使用几个模板引擎(主要用于日志记录),因此无需重新发明轮子。例如,你可能会觉得有趣

另请参阅此线程:

问题在于,在C中,#只是
string.Format
的语法糖衣包装。这些字符串被编译成相同的代码。以这段代码为例:

public string GetGreeting1(string name)
{
    return string.Format("Hello {0}!", name);
}

public string GetGreeting2(string name)
{
    return $"Hello {name}!";
}
两种方法的IL输出相同:

GetGreeting1:
IL_0000:  ldstr       "Hello {0}!"
IL_0005:  ldarg.1     
IL_0006:  call        System.String.Format
IL_000B:  ret         

GetGreeting2:
IL_0000:  ldstr       "Hello {0}!"
IL_0005:  ldarg.1     
IL_0006:  call        System.String.Format
IL_000B:  ret  
所以你的解决方案是完全有效的,我以前也用过。唯一可能的改进是,如果您打算进行大量替换,那么如果切换到使用
StringBuilder
,您可能会发现性能优势。你可能会在Nuget上找到一个为你做这件事的库,但这对你的目的来说可能太过分了

作为额外的,我为此制作了一个扩展类。另外,我还添加了一个方法,用于使用具有任意数量参数的对象,该对象使用反射进行替换:

public static class StringReplacementExtensions
{
    public static string Replace(this string source, Dictionary<string, string> values)
    {
        return values.Aggregate(
            source,
            (current, parameter) => current
                .Replace($"{{{parameter.Key}}}", parameter.Value));
    }

    public static string Replace(this string source, object values)
    {
        var properties = values.GetType().GetProperties();

        foreach (var property in properties)
        {
            source = source.Replace(
                $"{{{property.Name}}}", 
                property.GetValue(values).ToString());
        }

        return source;
    }
}
公共静态类StringReplacementExtensions
{
公共静态字符串替换(此字符串源,字典值)
{
返回值。聚合(
来源:,
(电流,参数)=>电流
.Replace($“{{{parameter.Key}}}”,parameter.Value));
}
公共静态字符串替换(此字符串源、对象值)
{
var properties=values.GetType().GetProperties();
foreach(属性中的var属性)
{
source=source.Replace(
$“{{{property.Name}}}”,
GetValue(values.ToString());
}
返回源;
}
}
然后像这样使用:

var source = "Hello {name}!";

//Using Dictionary:
var dict = new Dictionary<string, string> { { "name", "David" } };
var greeting1 = source.Replace(dict);
Console.WriteLine(greeting1);

//Using an anonymous object:
var greeting2 = source.Replace(new { name = "David" });
Console.WriteLine(greeting2);
var source=“你好{name}!”;
//使用字典:
var dict=新字典{{“name”,“David”};
var greeting1=源。替换(dict);
控制台写入线(欢迎1);
//使用匿名对象:
var greeting2=source.Replace(新的{name=“David”});
控制台写入线(欢迎2);

字符串插值只是
String.Format
的语法糖,你不能像这样使用预设字符串。@DavidG如果你有一个带有键值的字典和一个带有命名参数的字符串,你会如何映射它?你的最后一位代码是唯一的方法。如果你有很多替代品,你可能想考虑使用<代码> StringBuilder <代码>来执行。现在,为什么要投反对票!认真地不是我说的,这是一个有效的问题,只是不可能实现。
var source = "Hello {name}!";

//Using Dictionary:
var dict = new Dictionary<string, string> { { "name", "David" } };
var greeting1 = source.Replace(dict);
Console.WriteLine(greeting1);

//Using an anonymous object:
var greeting2 = source.Replace(new { name = "David" });
Console.WriteLine(greeting2);