alternatives to string.Format(".... {0}....{1}....",v1,v2) in .net?
string.Format() with it's "bla {0} bla" syntax is great. But sometimes I don't want to enumerate the placeholders. Instead I just want to map the variables sequentially in the pl开发者_如何学编程aceholders. Is there a library that can do that?
For instance, instead of
string.Format("string1={0}, string2={1}", v1, v2)
something like
string.Format("string1={*}, string2={*}", v1, v2)
There is now something called string interpolation in C# 6.0 so that
var name = "ozzy";
var x = string.Format("Hello {0}", name);
var y = $"Hello {name}";
equate to the same thing.
See https://msdn.microsoft.com/en-gb/magazine/dn879355.aspx
Just to add, you would frequently want to do a multi line string so that would just be:
var sql = $@"
SELECT
name, age, gender
FROM Users
WHERE UserId = '{userId}'
ORDER BY age asc";
Here's a possibly faster version using Regex.Replace
. Warning: no support for escaping the {*}, or nice error messages when you go out of range or don't supply enough arguments!
public static class ExtensionMethods
{
private static Regex regexFormatSeq = new Regex(@"{\*}", RegexOptions.Compiled);
public static string FormatSeq(this string format, params object[] args)
{
int i = 0;
return regexFormatSeq.Replace(format, match => args[i++].ToString());
}
}
You could accomplish this yourself by writing your own string extension coupled with the params keyword, assuming you're using .NET 3.5 or higher.
Edit: Got bored, the code is sloppy and error prone, but put this class in your project and using its namespace if necessary:
public static class StringExtensions
{
public static string FormatEx(this string s, params string[] parameters)
{
Regex r = new Regex(Regex.Escape("{*}"));
for (int i = 0; i < parameters.Length; i++)
{
s = r.Replace(s, parameters[i], 1);
}
return s;
}
}
Usage:
Console.WriteLine("great new {*} function {*}".FormatEx("one", "two"));
If I'm just writing out a series of variables without special formatting, I often prefer to just concatenate them e.g.:
Console.WriteLine("string1=" + var1 + " string2=" + var2);
Note the leading space in front of "string2", to separate the two results.
精彩评论