有没有办法String.Format
消息而不必指定{1}, {2},
等?是否可以采用某种形式的自动增量? (类似于普通的printf
)
答案 0 :(得分:5)
您可以使用named string formatting解决方案,这可以解决您的问题。
答案 1 :(得分:2)
害怕没有 - 它会把对象放到字符串中?使用printf,你仍然需要在某个地方放置说明符。
答案 2 :(得分:1)
有一个printf available here
的C#实现答案 3 :(得分:1)
我认为最好的方法是传递属性名称而不是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年出生的彼得格里芬通过了四年级。
答案 4 :(得分:0)
总是可以使用这种(未经测试的)方法,但我觉得它过于复杂:
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);
}
答案 5 :(得分:0)
我提出了这个问题,这又有点麻烦,但是我需要做的就是将可变数字或参数传递给我自己的函数,就像我使用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());
}
//...
}
答案 6 :(得分:0)
如果有人感兴趣,我已经修改了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;
}