2012-04-19 63 views
0

我試圖製作一個模板字符串,其佔位符由數據庫中的值替換,取決於其內部值。 即,模板應該是這樣的:根據內部值替換字符串中的值

No: {Job_Number} 
Customer: {Cust_Name} 
Action: {Action} 

模板可以改變任何東西,任何列值的括號內是.. 我找不出一個優雅的方式來獲得內部值並將其替換爲值...

回答

2

這一直是我對這個解決方案。

給你的格式字符串,你可以做這樣的事情:

// this is a MatchEvaluater for a regex replace 
string me_setFormatValue(Match m){ 
    // this is the key for the value you want to pull from the database 
    // Job_Number, etc... 
    string key = m.Groups[1].Value; 

    return SomeFunctionToGetValueFromKey(key); 
} 


void testMethod(){ 
    string format_string = @"No: {Job_Number} 
Customer: {Cust_Name} 
Action: {Action}"; 

    string formatted = Regex.Replace(@"\{([a-zA-Z_-]+?)\}", format_string, me_SetFormatValue); 
} 
+0

它的工作原理,但它的一個恥辱使用正則表達式這樣的事情,效率明智的。 – SimpleVar 2012-04-19 04:10:40

+0

我認爲性能受到的影響可以忽略不計,除非他在關鍵循環中出現這種情況。 – climbage 2012-04-19 04:18:52

+0

我喜歡這個理論..但是正則表達式不起作用,因爲\ {是一個未經過處理的逃生符號。 – michael 2012-04-19 05:10:10

0

我想要一個結構體或類來表示它,並重寫ToString。 您可能已經有了一個類,邏輯上你正在格式化爲一個字符串。

public class StringHolder 
{ 
    public int No; 
    public string CustomerName; 
    public string Action; 

    public override string ToString() 
    { 
     return string.Format("No: {1}{0}Customer: {2}{0}Action: {3}", 
          Environment.NewLine, 
          this.No, 
          this.CustomerName, 
          this.Action); 
    } 
} 

然後,您只需更改屬性,並將instance.ToString再次放入目標中以更新值。

您可以進行的StringHolder類更普遍的,像這樣:

public class StringHolder 
{ 
    public readonly Dictionary<string, string> Values = new Dictionary<string, string>(); 

    public override string ToString() 
    { 
     return this.ToString(Environment.NewLine); 
    } 

    public string ToString(string separator) 
    { 
     return string.Join(separator, this.Values.Select(kvp => string.Format("{0}: {1}", kvp.Key, kvp.Value))); 
    } 

    public string this[string key] 
    { 
     get { return this.Values[key]; } 
     set { this.Values[key] = value; } 
    } 
} 

然後用法是:

var sh = new StringHolder(); 

sh["No"] = jobNum; 
sh["Customer"] = custName; 
sh["Action"] = action; 

var s = sh.ToString();