标签:
先说下结论
using System.Diagnostics;
using RazorEngine;
using RazorEngine.Templating;
//脚本化的C#想写对还是有点麻烦的,还好Razor能给出有用的错误信息。
public class RazorPropertySetter<TEntity> where TEntity :class
{
string PropertyName;
bool Inited = false;
private RazorPropertySetter(){ }
public static RazorPropertySetter<TEntity> Create( string propertyName)
{
RazorPropertySetter<TEntity> rs = new RazorPropertySetter<TEntity>();
rs.PropertyName = propertyName;
return rs;
}
public void Set(TEntity entity , object value)
{
string cacheKey = entity.GetType().FullName + "--" + this.PropertyName;
DynamicViewBag viewBag = new DynamicViewBag();
viewBag.AddValue("PropertyValue", value);
if (Inited == false)
{
string template = "@{Model."+PropertyName+ "= ViewBag.PropertyValue;}";
Engine.Razor.RunCompile(template, cacheKey, typeof(TEntity), entity,viewBag);
Inited = true;
}
else
{
Engine.Razor.Run(cacheKey, typeof(TEntity), entity, viewBag);
}
}
}
//测试用类
public class TestData
{
public string Title { get; set; }
}
//测试代码
TestData data = new TestData();
data.Title = "V1";
RazorPropertySetter<TestData> setTitle = RazorPropertySetter<TestData>.Create("Title");
Stopwatch watch = new Stopwatch();
watch.Start();
setTitle.Set(data, "V00");
watch.Stop();
标签:
原文地址:http://www.cnblogs.com/ybst/p/5087832.html