2012-07-09 67 views
-1

我想創建這樣最好方式對象

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,但使用這將需要的代碼行數太多。我在這裏尋找一個簡約的解決方案。

+1

你說你想要一個字符串,然後你顯示一個返回類型爲DataSet的方法,這是一個錯字嗎? – James 2012-07-09 15:22:42

+0

不..我是goona在這個方法裏面的字符串。 – 2012-07-09 15:24:06

+0

已經上了:http://stackoverflow.com/questions/7689040/can-i-format-null-values-in-string-format – 2012-07-09 15:24:06

回答

7

你可以做這樣的事情:

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); 
+0

很好的解釋....正是我想要的... – 2012-07-09 15:30:40

2

請與覆蓋你喜歡的格式進行對象的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); 
    } 
} 

現在優勢做這樣的被:

  1. 在你的方法,你可以只使用1 Foo類型
  2. 當你調試和STO的參數在一個破發點,你添加的foo對象看,你會看到字符串表示
  3. 如果你確定要打印所有你需要做的,p是Console.WriteLine(富)
+0

爲什麼-2我只是說與他人相同的事情唯一的區別是我沒有給出完整的代碼 – HatSoft 2012-07-09 15:32:25

+0

請使用ToString()顯示您的完整代碼我很想看看事情的做法是不同的... – 2012-07-09 15:33:56

5
string foo = String.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}", 
          CategoryId, 
          Size ?? "null" ...);