C# 格式化字符串对象的最佳方法
我想创建一个像这样的字符串对象C# 格式化字符串对象的最佳方法,c#,string,C#,String,我想创建一个像这样的字符串对象 string data = "85-null-null-null-null-price-down-1-20"; // null if zero 我有一个这样的方法 public static DataSet LoadProducts(int CategoryId, string Size, string Colour, Decimal LowerPrice,
string data = "85-null-null-null-null-price-down-1-20"; // null if zero
我有一个这样的方法
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
}
我知道我可以使用
StringBuilder
,但是使用它需要太多的代码行。我在这里寻找一个最简单的解决方案。请用您喜欢的格式覆盖对象的ToString方法,并调用object.ToString()方法
评论后的请求示例:
public class Foo
{
public string Field1 {get; private set;}
public string Field2 {get; private set;}
public override string ToString()
{
return string.Format("Field1 = {0} , Field2 = {1}", Field1, Field2);
}
}
这样做的好处是:
您可以这样做:
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);
为方便起见,您可以创建扩展方法:
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";
}
并按如下方式使用它们:
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);
你说你想要一个字符串,然后你展示了一个返回类型为DataSet的方法,这是打字错误吗?不是。。我正在处理方法中的字符串。已经开始了:问题是为什么-1。这有什么不对吗?为什么-2我说的和其他人一样,唯一的区别是我没有给出完整的代码请使用ToString()显示您的完整代码我很想看看如何以不同的方式完成事情。。。
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);