简体   繁体   English

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

[英]C# How to treat a string variable as interpolated string?

the interpolated string is easy, just a string lead with $ sign.插值字符串很简单,只是一个带有 $ 符号的字符串前导。 But what if the string template is coming from outside of your code.但是,如果字符串模板来自您的代码之外怎么办。 For example assume you have a XML file containing following line:例如,假设您有一个包含以下行的 XML 文件:

<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv"/>

Then you can use LINQ to XML read the content of the attributes in.然后可以使用 LINQ 到 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");

Now how can I inject the date into the pathFrom variable and pathTo variable?现在如何将date注入pathFrom变量和pathTo变量?


If I have the control of the string itself, things are easy.如果我可以控制字符串本身,事情就简单了。 I can just do var xxx=$"C:\data\settle{date}.csv";我可以做var xxx=$"C:\data\settle{date}.csv"; But now, what I have is only the variable that I know contains the placeholder date但是现在,我所拥有的只是我知道的包含占位符date的变量

String interpolation is a compiler feature, so it cannot be used at runtime.字符串插值是编译器功能,因此不能在运行时使用。 This should be clear from the fact that the names of the variables in the scope will in general not be availabe at runtime.从 scope 中的变量名称通常在运行时不可用这一事实中应该清楚这一点。

So you will have to roll your own replacement mechanism.因此,您将不得不推出自己的替换机制。 It depends on your exact requirements what is best here.这取决于您的确切要求,这里最好。

If you only have one (or very few replacements), just do如果您只有一个(或很少有替代品),那就做

output = input.Replace("{date}", date);

If the possible replacements are a long list, it might be better to use如果可能的替换是一长串,最好使用

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

with

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

If you can get an IDictionary<string, string> mapping variable names to values you may simplify this to如果您可以获得 IDictionary<string, string> 将变量名称映射到值,则可以将其简化为

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

SOLUTION 1:解决方案 1:
If you have the ability to change something on xml template change {date} to {0}.如果您能够更改 xml 模板上的某些内容,请将 {date} 更改为 {0}。

<filePath from="C:\data\settle{0}.csv" to="D:\data\settle{0}.csv" />

Then you can set the value of that like this.然后你可以像这样设置它的值。

var elementString = string.Format(element.ToString(), DateTime.Now.ToString("MMddyyyy"));

Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" /> Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />

SOLUTION 2:解决方案 2:
If you can't change the xml template, then this might be my personal course to go.如果您无法更改 xml 模板,那么这可能是我对 go 的个人课程。

<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv" />

Set the placeholder like this.像这样设置占位符。

element.Attribute("to").Value = element.Attribute("to").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));
element.Attribute("from").Value = element.Attribute("from").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));

Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" /> Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />

I hope it helps.我希望它有所帮助。 Kind regards.亲切的问候。

You can't directly;你不能直接; the compiler turns your:编译器将您的:

string world = "world";
var hw = $"Hello {world}"

Into something like:变成这样的东西:

string world = "world";
var hw = string.Format("Hello {0}", world);

(It chooses concat, format or formattablestring depending on the situation) (根据情况选择concat、format或formattablestring)


You could engage in a similar process yourself, by replacing "{date" with "{0" and putting the date as the second argument to a string format, etc.您可以自己进行类似的过程,将“{date”替换为“{0”并将日期作为字符串格式的第二个参数等。

If you treat your original string as a user-input string (or anything that is not processed by the compiler to replace the placeholder, then the question is simple - just use String.Replace() to replace the placehoder {date} , with the value of the date as you wish. Now the followup question is: are you sure that the compiler is not substituting it during compile time, and leaving it untouched for handling at the runtime?如果您将原始字符串视为用户输入字符串(或编译器未处理的任何内容以替换占位符,那么问题很简单 - 只需使用String.Replace()替换占位符{date} ,您希望的日期值现在后续问题是:您确定编译器在编译期间没有替换它,并且在运行时保持不变以进行处理?

String interpolation allows the developer to combine variables and text to form a string.字符串插值允许开发人员将变量和文本组合成一个字符串。

Example Two int variables are created: foo and bar.示例 创建了两个 int 变量:foo 和 bar。

int foo = 34;
int bar = 42;

string resultString = $"The foo is {foo}, and the bar is {bar}.";

Console.WriteLine(resultString);

Output: Output:

The foo is 34, and the bar is 42.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM