我想创建一个像这样的字符串对象
string data = "85-null-null-null-null-price-down-1-20"; // null if zero
Run Code Online (Sandbox Code Playgroud)
我有这样的方法.
public static DataSet LoadProducts(int CategoryId, string Size,
string Colour, Decimal LowerPrice,
Decimal HigherPrice, string SortExpression,
int PageNumber, int PageSize,
Boolean OnlyClearance)
{
/// Code goes here
/// i am goona pass that string to one more method here
var result = ProductDataSource.Load(stringtoPass) // which accepts only the above format
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用a StringBuilder,但使用它需要太多代码行.我在这里寻找一个简约的解决方案.
你可以这样做:
return string.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}",
CategoryId,
Size ?? "null",
Colour ?? "null",
LowerPrice != 0 ? LowerPrice.ToString() : "null",
HigherPrice != 0 ? HigherPrice.ToString() : "null",
SortExpression ?? "null",
PageNumber != 0 ? PageNumber.ToString() : "null",
PageSize != 0 ? PageSize.ToString() : "null",
OnlyClearance);
Run Code Online (Sandbox Code Playgroud)
为方便起见,您可以创建扩展方法:
public static string NullStringIfZero(this int value)
{
return value != 0 ? value.ToString() : "null";
}
public static string NullStringIfZero(this decimal value)
{
return value != 0 ? value.ToString() : "null";
}
Run Code Online (Sandbox Code Playgroud)
并使用它们如下:
return string.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}",
CategoryId,
Size ?? "null",
Colour ?? "null",
LowerPrice.NullStringIfZero(),
HigherPrice.NullStringIfZero(),
SortExpression ?? "null",
PageNumber.NullStringIfZero(),
PageSize.NullStringIfZero(),
OnlyClearance);
Run Code Online (Sandbox Code Playgroud)
string foo = String.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}",
CategoryId,
Size ?? "null" ... );
Run Code Online (Sandbox Code Playgroud)