首頁 > 後端開發 > C++ > 如何在 C# 中實作命名字串格式化?

如何在 C# 中實作命名字串格式化?

Linda Hamilton
發布: 2025-01-03 15:44:40
原創
301 人瀏覽過

How Can I Achieve Named String Formatting in C#?

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板