Nvelocity - 创建一个随机数

时间:2016-08-16 18:50:27

标签: c# random nvelocity

处理一个项目,我只需要在页面中使用NVelocity生成随机数,而无需编辑C#背后的代码。我是NVelocity的新手,我看过各种各样的互联网,但是找不到答案。

感谢任何帮助。

注意:对于将此标记为可能重复的问题的用户。我试图调整该答案中列出的Velcocity / Java解决方案以适应NVelocity / C#而没有运气。我认为答案会有所不同。

1 个答案:

答案 0 :(得分:0)

NVelocity没有内置支持生成伪随机数,但如果您创建新的System.Random并将其添加到VelocityContext,您就可以从模板中访问它。

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

VelocityContext context = new VelocityContext();
context.Put("random", new Random());

using (StringWriter sw = new StringWriter())
{
    for (int i = 0; i < 5; i++)
    {
        velocityEngine.Evaluate(context, sw, "", "$random.Next(1, 100)\n");
    }

    Console.WriteLine(sw.ToString());
}