Какое наиболее читаемое использование string.format для длинных строк со многими параметрами?

StackOverflow https://stackoverflow.com/questions/1528210

Вопрос

Например:

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);

Это не создает очень читаемого кода, и по мере добавления все больше и большего количества параметров, он выглядит уроднее и более запутанно обнаружить, какой параметр поступает в каком слоте.

Я знаю, что это вопрос NOOB, и я думаю, что я только прошу отформатировать текст, чтобы быть более читаемым, но если есть лучший способ сделать это, я бы тоже хотел это знать.

Это было полезно?

Решение

Вы могли бы посмотреть на Класс StringBuilder и разделите сборку струны по нескольким линиям.

А Метод Appendformat (Спасибо, Джоэл) - это то, что вы хотите в этом случае.

Другие советы

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).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top