Is there a way to reduce the verbosity of using String.Format(...., p1, p2, p3)?
I often use String.Format()
because it makes the building of strings more readable and manageable.
Is ther开发者_StackOverflow社区e anyway to reduce its syntactical verbosity, e.g. with an extension method, etc.?
Logger.LogEntry(String.Format("text '{0}' registered", pair.IdCode));
public static void LogEntry(string message)
{
...
}
e.g. I would like to use all my and other methods that receive a string the way I use Console.Write()
, e.g.:
Logger.LogEntry("text '{0}' registered", pair.IdCode);
How about:
static void LogEntry(string format, params object[] args) {
Console.WriteLine(format, args); // For example.
}
Now you can call it like this:
Logger.LogEntry("text '{0}' registered", pair.IdCode);
If you control the Logger.LogEntry
method, you can simply add an overload that encompasses the string.format. Just declare the second parameter as a paramarray and you are good to go!
Yes, you can make an extension method named FormatWith, which lets you say things like:
Logger.LogEntry("I hate my {0}".FormatWith(itemName));
It should be easy enough to roll your own, but here's an example: http://james.newtonking.com/archive/2008/03/27/formatwith-string-format-extension-method.aspx
If Logger.LogEntry
is a static method outside of your control, then no; you can only add extension methods to instances. If it is your type, you could add:
public static void LogEntry(string format, params object[] args) {
... string.Format(format,args) ...
}
You could use the params keyword to combine all of the arguments after the first argument into an array and pass that array to String.Format.
static void FormatString(string myString, params string[] format)
{
Console.WriteLine(String.Format(myString, format));
}
精彩评论