What is the most readable use of String.Format for long strings with many parameters?
For instance:
String login = String.Format("computer={0}&ver={1}.{2}.{3}&from={4}&realcomputername={5}&type={6}&Channels={7}&Hotkeys={8}&ID={9}\r\n",
serviceConfig.Computer,
serviceConfig.Version.Major,
serviceConfig.Version.Minor,
serviceConfig.Version.Build,
userName,
Environment.MachineName,
type,
开发者_如何学运维 serviceConfig.ChannelsString,
serviceConfig.HotKeysString,
serviceConfig.AlarmGroupName);
This does not make for very readable code, and as more and more parameters get added, it looks uglier and is more confusing to find which parameter goes in which slot.
I know this is a noob question, and I think I'm only asking for how to format the text to be more readable, but if there's a better way to do this, I'd like to know that too.
You could look at the StringBuilder class and split the assembly of the string over several lines.
The AppendFormat method (thanks Joel) is what you want in this case.
String login = String.Format(
"computer={0}"+
"&ver={1}.{2}.{3}"+
"&from={4}"+
"&realcomputername={5}"+
"&type={6}"+
"&Channels={7}"+
"&Hotkeys={8}"+
"&ID={9}\r\n",
serviceConfig.Computer,
serviceConfig.Version.Major,
serviceConfig.Version.Minor,
serviceConfig.Version.Build,
userName,
Environment.MachineName,
type,
serviceConfig.ChannelsString,
serviceConfig.HotKeysString,
serviceConfig.AlarmGroupName);
Assuming you can use LINQ, you can shove your arguments into a Dictionary<string, string>
, then join the arguments together:
Dictionary<string, string> args = new Dictionary<string, string>
{
{"computer", serviceConfig.Computer},
{"ver", string.Format("{0}.{1}.{2}",
serviceConfig.Version.Major,
serviceConfig.Version.Minor,
serviceConfig.Version.Build)},
{"from", userName},
{"realcomputername", Environment.MachineName},
{"type", type},
{"Channels", serviceConfig.ChannelsString},
{"Hotkeys", serviceConfig.HotKeysString},
{"ID", serviceConfig.AlarmGroupName},
};
string login = string.Join("&", args.Select(arg =>
string.Format("{0}={1}", arg.Key, arg.Value)).ToArray());
This will be some miniscule amount slower and more memory-intensive than a simple string.Format, but it looks like you're about to make an HTTP request, so I can almost guarantee that it won't be the bottleneck.
That final line can also be pulled out into an extension method that you can use anytime you want to build a query string like this.
Also, it's important to note that since Dictionary does not preserve insertion order, you aren't guaranteed that the parameters in the query string will be in that exact order. That shouldn't matter, but in case it does you can replace the Dictionary with a List<KeyValuePair<string, string>>
(OrderedDictionary should also work).
精彩评论