简体   繁体   中英

Using an array in String.Format

Currently I'm working on an web-API dependent application. I have made a class with a lot of API strings like: /api/lol/static-data/{region}/v1/champion/{id} . Also I made a method:

public static String request(String type, Object[] param)
{
    return "";
}

This is going to do the requesting stuff. Because it's very different with each request type how many parameters are being used, I'm using an array for this. Now the question is, is it posssible to String.Format using an array for the paramaters while the keys in the strings are not numbers? Or does anyone know how to do this in a different way?

No, string.Format only supports index-based parameter specifications.

This:

"/api/lol/static-data/{region}/v1/champion/{id}"
                      ^^^^^^^^             ^^^^

will have to be handled using a different method, like string.Replace or a Regex .

You will need to:

  • Decide on the appropriate method for doing the replacements
  • Decide how an array with index-based values should map to the parameters, are they positional? ie. {region} is the first element of the array, {id} is the second, etc.?

Here is a simple LINQPad program that demonstrates how I would do it (though I would add a bit more error handling, maybe caching of the reflection info if this is executed a lot , some unit-tests, etc.):

void Main()
{
    string input = "/api/lol/static-data/{region}/v1/champion/{id}";
    string output = ReplaceArguments(input, new
    {
        region = "Europe",
        id = 42
    });
    output.Dump();
}

public static string ReplaceArguments(string input, object arguments)
{
    if (arguments == null || input == null)
        return input;

    var argumentsType = arguments.GetType();
    var re = new Regex(@"\{(?<name>[^}]+)\}");
    return re.Replace(input, match =>
    {
        var pi = argumentsType.GetProperty(match.Groups["name"].Value);
        if (pi == null)
            return match.Value;

        return (pi.GetValue(arguments) ?? string.Empty).ToString();
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM