C# 我可以在不指定数字的情况下将参数传递给 String.Format 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/561125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:12:50  来源:igfitidea点击:

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

c#.netstringformatting

提问by Hosam Aly

Is there a way to String.Formata message without having to specify {1}, {2},etc? Is it possible to have some form of auto-increment? (Similar to plain old printf)

有没有一种方法可以String.Format发送消息而无需指定{1}, {2},等?是否可以有某种形式的自动增量?(类似于普通的旧printf

采纳答案by mqp

Afraid not -- where would it put the objects into the string? Using printf, you still need to put specifiers in somewhere.

不怕——它将对象放入字符串的什么位置?使用 printf,您仍然需要在某处放置说明符。

回答by cbp

You can use a named string formattingsolution, which may solve your problems.

您可以使用命名字符串格式化解决方案,这可能会解决您的问题。

回答by Rune Grimstad

There is a C# implementation of printf available here

有一个C#实现的printf可在这里

回答by Hosam Aly

One could always use this (untested) method, but I feel it's over complex:

人们总是可以使用这种(未经测试的)方法,但我觉得它过于复杂:

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);
}

回答by FastAndBulbous

I came up with this, again it's a bit cumbersome but it works fine for what I needed to do which was to pass a variable number or arguments to my own function in the same way as I'd use WriteLine. I hope it helps somebody

我想出了这个,同样它有点麻烦,但它适用于我需要做的事情,即以与使用 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());
    }
    //...
}

回答by Ashkan Ghodrat

I think the best way would be passing the property names instead of Numbers. use this Method:

我认为最好的方法是传递属性名称而不是数字。使用此方法:

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;
    }

Imagine you have a Student Class with properties like: Name, LastName, BirthDateYear and use it like:

想象一下,你有一个学生类,其属性如下:姓名、姓氏、出生日期年,并像这样使用它:

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

and you'll get: Peter Griffin born in 1960 passed 4th grade.

你会得到:Peter Griffin 出生于 1960 年,通过了四年级。

回答by awsomedevsigner

If someone is interested, I have modified Ashkan's solution to be able to run it under WinRT:

如果有人感兴趣,我已经修改了 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;
}