用C#中的常量类创建字典

时间:2016-08-04 19:04:58

标签: c# dictionary

我有一个包含几个字符串常量的类:

 public class TemplateConstants
  {
    public static readonly string Type = "«Type»";
    public static readonly string Purpose = "«Purpose»";
    public static readonly string FirstName = "«FirstName»";
 ....
 }

每个代表一个“占位符”。我有一个包含各种占位符的HTML文档。在我的Web API控制器(C#)中,我将逐个替换这些占位符:

 string doc = string.Empty;
 string htmltest = System.IO.File.ReadAllText     
(HttpContext.Current.Server.MapPath(@"~\Templates\Template.html"));
doc = htmltest.Replace(TemplateConstants.ApplicationType, applicationType);
        doc = doc.Replace(TemplateConstants.LoanPurpose, loanType);
        doc = doc.Replace(ApplicationDocTemplateConstants.BorrowerFirstName, FirstName);
.....

有没有办法在这里使用字典,以便我可以以某种方式循环遍历文件并根据字典进行替换(而不是一次只进行一次替换)?

2 个答案:

答案 0 :(得分:0)

我将静态字符串转换为常量,然后添加了一个将常量转换为字典的方法。

public class TemplateConstants
{
    public const string Type = "«Type»";
    public const string Purpose = "«Purpose»";
    public const string FirstName = "«FirstName»";

    private static readonly Lazy<Dictionary<string, string>> ConstantsDictionary =
        new Lazy<Dictionary<string, string>>(CreateDictionary);

    public static Dictionary<string, string> AsDictionary()
    {
        return ConstantsDictionary.Value;
    }

    private static Dictionary<string, string> CreateDictionary()
    {
        var fields = typeof(TemplateConstants)
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

        var constants = fields.Where(f => f.IsLiteral && !f.IsInitOnly).ToList();
        var result = new Dictionary<string, string>();
        var instance = new TemplateConstants();

        // Up to you if you want to filter the constants further to only include those
        // with string values.
        constants.ForEach(constant => result.Add(constant.Name, constant.GetValue(instance).ToString()));
        return result;
    }
}

[TestClass]
public class TestTemplateConstants
{
    [TestMethod]
    public void TestDictionary()
    {
        var dictionary = TemplateConstants.AsDictionary();
        Assert.AreEqual(dictionary["Type"],TemplateConstants.Type);
    }
}

答案 1 :(得分:-1)

在程序上使用Razor视图引擎,如下例所示: http://razorengine.codeplex.com/ (nuget RazorEngine)

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

class Program
{
    static void Main(string[] args)
    {
        string template = "Hello @Model.Types, welcome to RazorEngine!";
        var result =
            Engine.Razor.RunCompile(template, "templateKey", null, new TemplateConstants());

        Console.WriteLine(result);
    }
}

public class TemplateConstants
{
    public readonly string Types = "Some type";
    public readonly string Purpose = "«Purpose»";
    public readonly string FirstName = "«FirstName»";

}

当然你的模板应该是Razor语法 喜欢:

<html>
...
<div>@Model.Purpose</div>
<div>@Model.FirstName</div>
...
</html>

另见:https://github.com/Antaris/RazorEngine