来自数据库的字符串插值格式的字符串在 C# 代码中使用它

Jas*_*yug 3 c# string-interpolation formattablestring

例如,我有一个从数据库检索到的字符串。

string a = "The quick brown {Split[0]}   {Split[1]} the lazy dog";
string b = "jumps over";
Run Code Online (Sandbox Code Playgroud)

然后我将执行这段代码。

String[] Split= b.Split(' ');
String c= $"{a}";
Console.Writeline(c):
Run Code Online (Sandbox Code Playgroud)

这个方法行不通。您知道这如何成为可能吗?我感谢您的帮助。^-^

Oli*_*bes 6

内插的字符串由编译器解释。即,例如在

string a = "fox";
string b = "jumps over";

// this line ...
string s = $"The quick brown {a} {b} the lazy dog";
Run Code Online (Sandbox Code Playgroud)

...转换为

string s = String.Format("The quick brown {0} {1} the lazy dog", a, b);
Run Code Online (Sandbox Code Playgroud)

...由编译器。

因此,您不能在运行时对(常规)字符串中的变量名称使用字符串插值。

您必须在运行时使用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):
Run Code Online (Sandbox Code Playgroud)

请注意,运行时,局部变量的名称是未知的。如果反编译已编译的 C# 程序,反编译的代码将包含局部变量的通用名称l1,例如l2等(取决于反编译器)。