目前,我正在开发一个依赖于web API的应用程序。我用很多API字符串(如:/api/lol/static-data/{region}/v1/champion/{id} )创建了一个类。我还做了一个方法:
public static String request(String type, Object[] param)
{
return "";
}这将完成要求的事情。由于每个请求类型使用多少个参数非常不同,所以我为此使用了一个数组。现在的问题是,在字符串中的键不是数字的情况下,String.Format是否可以为参数使用数组?还是有人知道怎么用不同的方式做这件事?
发布于 2014-02-05 09:06:12
不,string.Format只支持基于索引的参数规范.
这是:
"/api/lol/static-data/{region}/v1/champion/{id}"
^^^^^^^^ ^^^^必须使用不同的方法来处理,如string.Replace或Regex。
你需要:
{region}是数组的第一个元素,{id}是第二个元素,等等?下面是一个简单的LINQPad程序,它演示了我将如何做到这一点(尽管我会增加一些错误处理,如果经常执行反射信息,可能会缓存反射信息,一些单元测试等等):
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();
});
}https://stackoverflow.com/questions/21572609
复制相似问题