2012-04-19 56 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();