我有一个方法如下所示。
public IResults GetResults(
string code = "",
string id = "",
DateTime? registerDate = null,
IEnumerable<Category> type = null,
int pageNum = 1,
bool all = false)
{
....
........
}
对于每个非null或非空参数,我希望将参数名称和值附加到URI字符串。
例如,如果参数code
是非空的string
,那么我希望将其作为result/?
附加到标准URI results/?code=passedcodevalue
。如果它是空的,那么就没有必要追加它。
同样,这些是构造URI的规则:
当code
或id
不为空时,请将其附加到 - results/?
- 作为
results /?code = abc&amp; id = xyz
registerDate
未归零时,请将其附加到 - results/?
- as
结果/码= ABC&安培;?ID = XYZ&安培; registerdate = 2004-06-29
type
未归零时,请将其附加到 - results/?
- as
结果/码= ABC&安培;?ID = XYZ&安培; registerdate = 2004-06-29&安培;类型= QWERTY
当pagenum
不是1时,请将其附加到 - results/?
- as
结果/码= ABC&安培;?ID = XYZ&安培; registerdate = 2004-06-29&安培;类型= QWERTY&安培;页次= 5
当all
不为false时将其附加到 - results/?
- as
结果/码= ABC&安培;?ID = XYZ&安培; registerdate = 2004-06-29&安培;类型= QWERTY&安培;页次= 5&安培;所有=真
执行此操作的最佳和通用方法是什么?
答案 0 :(得分:0)
试试这个:
public string GetResults(
string code = "",
string id = "",
DateTime? registerDate = null,
IEnumerable<Category> type = null,
int pageNum = 1,
bool all = false)
{
var result = "results/?";
var firstFound = false; //Used for add & to string
for (int i = 0; i < 6; i++)
{
var partial = string.Empty;
switch (i)
{
case 0:
partial = GetIfNotEmpty("code", code);
break;
case 1:
partial = GetIfNotEmpty("id", id);
break;
case 2:
partial = GetIfNotEmpty("registerDate", registerDate);
break;
case 3:
partial = GetIfNotEmpty("type", type);
break;
case 4:
partial = GetIfNotEmpty("pageNum", pageNum);
break;
default:
partial = GetIfNotEmpty("all", all);
break;
}
if (string.IsNullOrWhiteSpace(partial))
continue;
if (firstFound)
result += "&";
else
firstFound = true;
result += partial;
}
return result;
}
private string GetIfNotEmpty<T>(string name, T value)
{
if (value == null)
return string.Empty;
if (value is IEnumerable)
{
var enumerableFinalString = string.Empty;
foreach (var item in ((IEnumerable)value))
{
enumerableFinalString += item.ToString();
}
return string.Format("{0}={1}", name, enumerableFinalString);
}
return string.Format("{0}={1}", name, value.ToString());
}