C# 中的命名字串格式化
在Python 等程式語言中,您可以按名稱而不是位置格式化字串。例如,您可以有這樣的字串:
print '%(language)s has %(#)03d quote types.' % \ {'language': "Python", "#": 2}
這將列印「Python has 002 quote types.」
在C# 中,沒有用於格式化字串的內建方法按名字。但是,有幾種方法可以實現類似的結果。
使用字典
一種選擇是使用字典將變數名稱對應到其值。然後,您可以將字典傳遞給自訂字串格式化方法,該方法使用變數名稱來格式化字串。
這是一個範例:
public static string FormatStringByName(string format, Dictionary<string, object> values) { // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the dictionary. var formattedString = regex.Replace(format, match => values[match.Groups[1].Value].ToString()); return formattedString; }
您可以像這樣使用此方法:
var values = new Dictionary<string, object> { { "some_variable", "hello" }, { "some_other_variable", "world" } }; string formattedString = FormatStringByName("{some_variable}: {some_other_variable}", values);
使用字串插值
中C# 6.0 及更高版本,您可以使用字串插值按名稱格式化字串。字串插值是一項功能,可讓您將表達式直接嵌入到字串中。
這裡是一個範例:
string formattedString = $"{some_variable}: {some_other_variable}";
這將列印「hello: world」。
擴充方法
另一個選擇是使用擴充方法來新增命名字串格式化功能到字串類別。以下是您可以使用的擴充方法的範例:
public static class StringExtensions { public static string FormatByName(this string format, object values) { // Get the type of the values object. var type = values.GetType(); // Get the properties of the values object. var properties = type.GetProperties(); // Create a regular expression to match variable names in the format string. var regex = new Regex(@"\{(.*?)\}"); // Replace each variable name with its value from the values object. var formattedString = regex.Replace(format, match => { var property = properties.FirstOrDefault(p => p.Name == match.Groups[1].Value); if (property != null) { return property.GetValue(values).ToString(); } else { return match.Groups[1].Value; } }); return formattedString; } }
您可以像這樣使用此擴充方法:
string formattedString = "{some_variable}: {some_other_variable}".FormatByName(new { some_variable = "hello", some_other_variable = "world" });
以上是如何在 C# 中實作命名字串格式化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!