2010-03-09 49 views
0

我使用字符串模板來呈現一些內容,但內容可以是可變的所以不知道如何將它傳遞(使用.NET/C#)StringTemplate的.NET動態對象

基本的想法是我有一個List >這需要以參數結束,例如

List<KeyValuePair<string, object>> ret = new List<KeyValuePair<string, object>>(); 
ret.Add(new KeyValuePair<string, object>("elem1", true)); 
ret.Add(new KeyValuePair(string, object>("elem2", false)); 

現在我想這些在字符串模板顯示爲:

$ item.elem1 $ $ item.elem2 $

我可以讓他們爲$ elem1 $或$ elem2時$但我需要它們在一個結構內。所以我實際上需要說服我傳入的屬性爲elem1和elem2的對象的字符串模板setAttribute,實際上我有一個KeyValuePairs列表。

謝謝

回答

4

其實很小的重寫應該工作。你需要使用字典,你甚至可以嵌套它們(使用ST 3.2):

[Test] 
public void When_Building_Text_With_A_Dictionary_As_The_Attributes_It_Should_Map_Members_To_Keys() 
{ 
    IDictionary<string, object> ret = new Dictionary<string, object>(); 
    ret["elem1"] = true; 
    ret["elem2"] = false; 

    var nestedObj = new Dictionary<string, object>(); 
    nestedObj["nestedProp"] = 100; 
    ret["elem3"] = nestedObj; 

    var template = new StringTemplate("$elem1$ or $elem2$ and value: $elem3.nestedProp$"); 
    template.Attributes = ret; 

    StringBuilder sb = new StringBuilder(); 
    StringWriter writer = new StringWriter(sb); 
    template.Write(new NoIndentWriter(writer)); 
    writer.Flush(); 

    var renderedText = sb.ToString(); 

    Assert.That(renderedText, Is.EqualTo("True or False and value: 100")); 
} 

我和同事正在尋找複製STST(ST獨立工具)時,它使用JSON作爲性功能,我們建立了一個簡單的JObject到字典轉換器,我可以發佈該代碼和一個例子,如果它對你有用,它只有20行。

+0

最後,我最終使用CS-Script來運行一些動態創建的代碼,包含對象......這對我們很有用,因爲我們已經在同一個項目的其他地方運行了動態代碼......但如果我們需要更多的優化,可能會回到它並使用您的解決方案。 – 2010-04-17 10:08:27

+0

這似乎並沒有回答上面的問題? – Xian 2011-01-16 09:04:33

0

ExpandoObject的成員可以在運行時動態添加和刪除。

+1

在這個時間點,Expando對象似乎不適用於StringTemplate。 – shashi 2013-06-13 11:16:44