C# 如何将字符串变量视为内插字符串?

Gen*_*n.L 3 c# string format

插入的字符串很简单,只需一个带有 $ 符号的字符串。但是如果字符串模板来自代码外部怎么办?例如,假设您有一个包含以下行的 XML 文件:

<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv"/>
Run Code Online (Sandbox Code Playgroud)

然后就可以使用LINQ to XML读取其中的属性内容了。

//assume the ele is the node <filePath></filePath>
string pathFrom = ele.Attribute("from").value;
string pathTo = ele.Attibute("to").value;
string date = DateTime.Today.ToString("MMddyyyy");
Run Code Online (Sandbox Code Playgroud)

现在我怎样才能将 注入datepathFrom变量和pathTo变量中?


如果我能控制字符串本身,事情就很容易了。我可以做var xxx=$"C:\data\settle{date}.csv";但是现在,我所拥有的只是我知道包含占位符的变量date

Kla*_*ter 6

字符串插值是编译器功能,因此不能在运行时使用。从作用域中的变量名称通常在运行时不可用的事实来看,这一点应该很清楚。

所以你必须推出自己的替换机制。这取决于您的具体要求,这里什么是最好的。

如果您只有一个(或很少的替代品),只需这样做

output = input.Replace("{date}", date);
Run Code Online (Sandbox Code Playgroud)

如果可能的替换列表很长,那么最好使用

output = Regex.Replace(input, @"\{\w+?\}", 
    match => GetValue(match.Value));
Run Code Online (Sandbox Code Playgroud)

string GetValue(string variable)
{
    switch (variable)
    {
    case "{date}":
        return DateTime.Today.ToString("MMddyyyy");
    default:
        return "";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您可以获得 IDictionary<string, string> 将变量名称映射到值,您可以将其简化为

output = Regex.Replace(input, @"\{\w+?\}", 
    match => replacements[match.Value.Substring(1, match.Value.Length-2)]);
Run Code Online (Sandbox Code Playgroud)