簡體   English   中英

我可以在不指定數字的情況下將參數傳遞給String.Format嗎?

[英]Can I pass parameters to String.Format without specifying numbers?

有沒有辦法讓String.Format一條消息而不必指定{1}, {2},等? 是否可以采用某種形式的自動增量? (類似普通的舊printf

您可以使用命名的字符串格式化解決方案,這可以解決您的問題。

不敢 - 它會把對象放到字符串中的哪個位置? 使用printf,您仍然需要在某處放置說明符。

有一個C#實現的printf 可在這里

我認為最好的方法是傳遞屬性名稱而不是Numbers。 使用此方法:

using System.Text.RegularExpressions;
using System.ComponentModel;

public static string StringWithParameter(string format, object args)
    {
        Regex r = new Regex(@"\{([A-Za-z0-9_]+)\}");

        MatchCollection m = r.Matches(format);

        var properties = TypeDescriptor.GetProperties(args);

        foreach (Match item in m)
        {
            try
            {
                string propertyName = item.Groups[1].Value;
                format = format.Replace(item.Value, properties[propertyName].GetValue(args).ToString());
            }
            catch
            {
                throw new FormatException("The string format is not valid");
            }
        }

        return format;
    }

想象一下,你有一個學生類,其屬性如:Name,LastName,BirthDateYear,並使用它像:

 Student S = new Student("Peter", "Griffin", 1960);
 string str =  StringWithParameter("{Name} {LastName} Born in {BithDate} Passed 4th grade", S);

你會得到:1960年出生的彼得格里芬通過了四年級。

如果有人有興趣,我已經修改了Ashkan的解決方案,以便能夠在WinRT下運行它:

/// <summary>
/// Formats the log entry.
/// /// Taken from:
/// http://stackoverflow.com/questions/561125/can-i-pass-parameters-to-string-format-without-specifying-numbers
/// and adapted to WINRT
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The arguments.</param>
/// <returns></returns>
/// <exception cref="System.FormatException">The string format is not valid</exception>
public static string FormatLogEntry(string format, object args)
{
    Regex r = new Regex(@"\{([A-Za-z0-9_]+)\}");

    MatchCollection m = r.Matches(format);

    var properties = args.GetType().GetTypeInfo().DeclaredProperties;

    foreach (Match item in m)
    {
        try
        {
            string propertyName = item.Groups[1].Value;
            format = format.Replace(item.Value, properties.Where(p=>p.Name.Equals(propertyName))
                .FirstOrDefault().GetValue(args).ToString());
        }
        catch
        {
            throw new FormatException("The string format is not valid");
        }
    }

    return format;
}

人們總是可以使用這個(未經測試的)方法,但我覺得它過於復雜:

public static string Format(char splitChar, string format,
                            params object[] args)
{
    string splitStr = splitChar.ToString();
    StringBuilder str = new StringBuilder(format + args.Length * 2);
    for (int i = 0; i < str.Length; ++i)
    {
        if (str[i] == splitChar)
        {
            string index = "{" + i + "}";
            str.Replace(splitStr, index, i, 1);
            i += index.Length - 1;
        }
    }

    return String.Format(str.ToString(), args);
}

我想出了這個,再次它有點麻煩,但它適用於我需要做的事情,即將變量數或參數傳遞給我自己的函數,就像我使用WriteLine一樣。 我希望它對某人有所幫助

protected void execute(String sql, params object[] args)
{
    for (int i = 0; i < args.Count(); i++ )
    {
        sql = sql.Replace(String.Format("{{{0}}}", i), args[i].ToString());
    }
    //...
}

暫無
暫無

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

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