2009-09-15 113 views
6

它真的很煩人C#似乎強迫你顯式地命名String.Format中的每個參數的索引,如果你想添加另一個參數,你必須重新索引字符串或放置最後你的新參數。String.Format參數順序煩擾

有沒有辦法讓C#自動執行此操作?

例如(我知道這是沒有意義的學究,它僅僅是一個例子:)

我開始:

String.Format("{0} {1} {1} {2} {3}", a, b, c, d) 

,如果我想在開始添加一個參數,我可以做下列之一:

String.Format("{4} {0} {1} {1} {2} {3}", a, b, c, d, e) 
String.Format("{0} {1} {2} {2} {3} {4}", e, a, b, c, d) 
在Delphi

比如我可以做的這相當於:

String.Format("{} {} {} {2} {} {}", e, a, b, c, d) 
+0

C#和delphi中的兩行都返回相同的東西嗎? – Beatles1692 2009-09-15 11:43:45

回答

23

嘛,沒有什麼在C#中做次是自動爲你。你總是可以寫自己的方法來做到這一點,但坦率地說,我會發現它不太可讀。要做更多的想法(海事組織)來理解你的最後一條線比以前的要好。當你點擊{2}你必須在精神上走回頭路,與{3}取代先前的項目跳過{2}

我個人更喜歡代碼,需要更長的時間打字,但清楚地閱讀。

+7

+1:最初寫作時,可維護性應該總是能夠節省一筆積蓄。 – Richard 2009-09-15 11:38:43

+5

+1「計算機程序應該被設計爲供人閱讀並且被計算機偶爾運行」 – 2009-09-15 11:39:53

+0

String.Format(「{a} {b} {b} {c} {d}」,a,b,c ,d)?可以在.NET 4.0中添加嗎?也許編譯器可以幫助。還是新的DLR?我可能在這裏錯過了一些東西,但它會很好... – 2009-09-15 12:52:08

2

您請求的功能不是框架的一部分。這裏有一個很好的擴展方法,我發現它提供了命名參數c#。我認爲馬克格雷維爾發佈了它或者其他那些大師之一。

 static readonly Regex rePattern = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled); 


    /// <summary> 
    /// Shortcut for string.Format. Format string uses named parameters like {name}. 
    /// 
    /// Example: 
    /// string s = Format("{age} years old, last name is {name} ", new {age = 18, name = "Foo"}); 
    /// 
    /// </summary> 
    /// <param name="format"></param> 
    /// <param name="values"></param> 
    /// <returns></returns> 
    public static string FN<T>(this string pattern, T template) 
    { 
     Dictionary<string, string> cache = new Dictionary<string, string>(); 
     return rePattern.Replace(pattern, match => 
     { 
      string key = match.Groups[1].Value; 
      string value; 

      if (!cache.TryGetValue(key, out value)) 
      { 
       var prop = typeof(T).GetProperty(key); 
       if (prop == null) 
       { 
        throw new ArgumentException("Not found: " + key, "pattern"); 
       } 
       value = Convert.ToString(prop.GetValue(template, null)); 
       cache.Add(key, value); 
      } 
      return value; 
     }); 
    } 
+0

不錯,但有一個主要的性能影響! – ShloEmi 2016-07-17 08:49:18

1

即使C#不能爲您做到這一點,該工具可以在這裏幫助。

例如,如果您在字符串中的參數多於字符串後,Resharper會警告您。我查看是否支持Resharper中的參數重新排序,但在這種情況下它不是(R#支持更改方法簽名,但在這裏沒有幫助)。

看DevEx的Code Rush。該工具很可能具有你所需要的。

1

我知道這是舊的,我同意喬恩。即使使用大格式字符串(請參閱下面的代碼示例),如果必須添加內容,它仍然只需要1分鐘時間就可以重做項目的索引位置,並且我發現它更易於維護和可讀,然後嘗試創建使過程自動化的方法。自動化的問題是,當我在幾周後嘗試查看代碼時,您無法一眼就明白。另外,一旦你很好地學習了Visual Studio並學習使用塊編輯模式和其他一些高級功能之類的東西,你可以非常高效。

//----------------------------------------------------------------------------- 
// <copyright file="ShellForm.cs" company="DCOM Productions"> 
//  Copyright (c) DCOM Productions. All rights reserved. 
// </copyright> 
//----------------------------------------------------------------------------- 

string updateCommandText = string.Format("UPDATE `moh`.`moh` SET ageact = '{0}', branch = '{1}', cemetary = '{2}', citation = '{3}', citycement = '{4}', cdateact = '{5}', cdateaward = '{6}', cdatebirth = '{7}', cdatedeath = '{8}', namefirst = '{9}', namelast = '{10}', placeact = '{11}', placeenter = '{12}', presat = '{13}', presby = '{14}', rankact = '{15}', rankawd = '{16}', rankhigh = '{17}', synopsis = '{18}', unit = '{19}', war = '{20}', imgfile = '{21}' WHERE ID = '{22}'", 
    /* {0} */ uxAgeAct.Text.Replace("'", "''"), 
    /* {1} */ uxBranch.Text.Replace("'", "''"), 
    /* {2} */ uxCemetary.Text.Replace("'", "''"), 
    /* {3} */ uxCitation.Text.Replace("'", "''"), 
    /* {4} */ uxCityCemetary.Text.Replace("'", "''"), 
    /* {5} */ uxDateAct.Text.Replace("'", "''"), 
    /* {6} */ uxDateAward.Text.Replace("'", "''"), 
    /* {7} */ uxDateBirth.Text.Replace("'", "''"), 
    /* {8} */ uxDateDiceased.Text.Replace("'", "''"), 
    /* {9} */ uxNameFirst.Text.Replace("'", "''"), 
    /* {10} */ uxNameLast.Text.Replace("'", "''"), 
    /* {11} */ uxPlaceAct.Text.Replace("'", "''"), 
    /* {12} */ uxPlaceEnter.Text.Replace("'", "''"), 
    /* {13} */ uxPresentedAt.Text.Replace("'", "''"), 
    /* {14} */ uxPresentedBy.Text.Replace("'", "''"), 
    /* {15} */ uxRankAct.Text.Replace("'", "''"), 
    /* {16} */ uxRankAwarded.Text.Replace("'", "''"), 
    /* {17} */ uxRankHigh.Text.Replace("'", "''"), 
    /* {18} */ uxSynopsis.Text.Replace("'", "''"), 
    /* {19} */ uxUnit.Text.Replace("'", "''"), 
    /* {20} */ uxWar.Text.Replace("'", "''"), 
    /* {21} */ uxImgFile.Text.Replace("'", "''"), 
    /* {22} */ dataRow["ID"].ToString()); 
3

由於Visual Studio的2015年,你可以一邊使用步驟這個Interpolated Strings問題(它的編譯器的把戲,所以它不會不管你針對.NET Framework的版本)。

然後,該代碼看起來是這樣的

string txt = $"{person.ForeName} is not at home {person.Something}"; 

我認爲它使代碼更易讀且不易出錯。