簡體   English   中英

C# 如何將字符串變量視為插值字符串?

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

插值字符串很簡單,只是一個帶有 $ 符號的字符串前導。 但是,如果字符串模板來自您的代碼之外怎么辦。 例如,假設您有一個包含以下行的 XML 文件:

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

然后可以使用 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");

現在如何將date注入pathFrom變量和pathTo變量?


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

字符串插值是編譯器功能,因此不能在運行時使用。 從 scope 中的變量名稱通常在運行時不可用這一事實中應該清楚這一點。

因此,您將不得不推出自己的替換機制。 這取決於您的確切要求,這里最好。

如果您只有一個(或很少有替代品),那就做

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

如果可能的替換是一長串,最好使用

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

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

如果您可以獲得 IDictionary<string, string> 將變量名稱映射到值,則可以將其簡化為

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

解決方案 1:
如果您能夠更改 xml 模板上的某些內容,請將 {date} 更改為 {0}。

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

然后你可以像這樣設置它的值。

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

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

解決方案 2:
如果您無法更改 xml 模板,那么這可能是我對 go 的個人課程。

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

像這樣設置占位符。

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" />

我希望它有所幫助。 親切的問候。

你不能直接; 編譯器將您的:

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

變成這樣的東西:

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

(根據情況選擇concat、format或formattablestring)


您可以自己進行類似的過程,將“{date”替換為“{0”並將日期作為字符串格式的第二個參數等。

如果您將原始字符串視為用戶輸入字符串(或編譯器未處理的任何內容以替換占位符,那么問題很簡單 - 只需使用String.Replace()替換占位符{date} ,您希望的日期值現在后續問題是:您確定編譯器在編譯期間沒有替換它,並且在運行時保持不變以進行處理?

字符串插值允許開發人員將變量和文本組合成一個字符串。

示例 創建了兩個 int 變量:foo 和 bar。

int foo = 34;
int bar = 42;

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

Console.WriteLine(resultString);

Output:

The foo is 34, and the bar is 42.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM