[英]A string with string interpolation format from database use it in C# code
例如,我有一個從數據庫中檢索到的字符串。
string a = "The quick brown {Split[0]} {Split[1]} the lazy dog";
string b = "jumps over";
然后我將執行此代碼。
String[] Split= b.Split(' ');
String c= $"{a}";
Console.Writeline(c):
這種方法不起作用。 你知道這怎么可能嗎? 我感謝您的幫助。 ^-^
內插字符串由編譯器解釋。 即,例如在
string a = "fox";
string b = "jumps over";
// this line ...
string s = $"The quick brown {a} {b} the lazy dog";
...轉換為
string s = String.Format("The quick brown {0} {1} the lazy dog", a, b);
...由編譯器。
因此,您不能在運行時將字符串插值與(常規)字符串中的變量名一起使用。
您必須在運行時使用String.Format
:
string a = "The quick brown {0} {1} the lazy dog";
string b = "fox;jumps over";
string[] split = b.Split(';');
string c = String.Format(a, split[0], split[1]);
Console.Writeline(c):
請注意,在運行時,局部變量的名稱是未知的。 如果您反編譯已編譯的 C# 程序,反編譯的代碼將包含局部變量的通用名稱,例如l1
、 l2
等(取決於反編譯器)。
正如 LasseV.Karlsen 和 Hans Kesting 所解釋的,您可以在這種情況下使用string.Format
。 讓我給你一個簡單的例子:
string b = "jumps over";
string[] Split = b.Split(' ');
string c = string.Format("The quick brown fox {0} {1} the lazy dog.",Split[0], Split[1]);
Console.WriteLine(c);
請注意,這只是string.Format
的一個示例,同時還有無數其他用途。 了解有關此方法的更多信息的最佳資源可能是Microsoft 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.