2014-01-15 37 views
0

添加一個字典,像這樣的價值觀:避免Nvelocity拋出異常,當辭典鍵不存在

Dictionary<string, string> CustomArray = new Dictionary<string, string>(); 
CustomArray.Add("customValue1", "mydata"); 
this.velocityContext.Put("array", CustomArray); 

使用模板引擎這樣的:

Velocity.Init(); 
string template = FileExtension.GetFileText(templateFilePath); 
var sb = new StringBuilder(); 

using(StringWriter sw = new StringWriter(sb)) 
{ 
    using(StringReader sr = new StringReader(template)) 
    { 
     Velocity.Evaluate(
      this.velocityContext, 
      sw, 
      "test template", 
      sr); 
    } 
} 
return sb.ToString(); 

模板訪問的是這樣的:

('customValue1')

$ array.Get_Item('customValu' e2')

customValue1檢索得很好,但customValue2拋出KeyNotFoundException,因爲該字典中不存在該鍵。如何在不刪除引發KeyNotFoundException的行的情況下生成模板?

我已經看過了Apache的速度指引,但我不知道如何添加這個(https://velocity.apache.org/tools/devel/creatingtools.html#Be_Robust

回答

2

這看起來像NVelocity的操控.NET的Dictionary<K,V>的缺陷。由於NVelocity起源於Java支持的泛型之前的Velocity,並且因爲NVelocity是舊代碼庫,所以我嘗試使用非通用Hashtable,並且按預期工作。由於該映射未在NVelocity模板中輸入,因此應該改變切換類以解決此缺陷。

隨意記錄缺陷,但沒有拉動請求,它不太可能被修復。

VelocityEngine velocityEngine = new VelocityEngine(); 
velocityEngine.Init(); 

Hashtable dict = new Hashtable(); 
dict.Add("customValue1", "mydata"); 

VelocityContext context = new VelocityContext(); 
context.Put("dict", dict); 

using (StringWriter sw = new StringWriter()) 
{ 
    velocityEngine.Evaluate(context, sw, "", 
     "$dict.get_Item('customValue1')\r\n" + 
     "$dict.get_Item('customValue2')\r\n" + 
     "$!dict.get_Item('customValue2')" 
    ); 

    Assert.AreEqual(
     "mydata\r\n" + 
     "$dict.get_Item('customValue2')\r\n" + 
     "", 
     sw.ToString()); 
} 
+0

你是絕對正確的,非常感謝! – jmelhus