문제

I often use String.Format() because it makes the building of strings more readable and manageable.

Is there 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));
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top