如果是引用类型,需要通过构造函数创建对象,像前面用于,这里我们也用Expression来构建一个Func<object>类型的委托来优化,它调用了ReflectionUtil.GetConstructorDelegate方法。实现如下:
/// <summary>
/// 获取构造函数委托
/// </summary>
/// <param name="type">实例类型</param>
/// <returns></returns>
public static Func<object> GetConstructorDelegate(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
if (ci == null)
{
throw new MissingMemberException("类型必须有一个无参public构造函数!");
}
NewExpression newExp = Expression.New(type);
Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(newExp);
return lambda.Compile();
}
最后再输出结果时,如果是Get请求,并且需要缓存,我们还需要设置一下Response.Cache。如下:
private static void EndRequest(HttpContext context, object data, int outPutCache, ContentType contentType)
{
HttpResponse response = context.Response;
if (outPutCache != 0)
{
if (string.Compare(context.Request.HttpMethod, "GET", true) == 0)
{
if (outPutCache > 0)
{
response.Cache.SetCacheability(HttpCacheability.Public);
response.Cache.SetMaxAge(new TimeSpan(0, 0, outPutCache));
response.Cache.SetExpires(DateTime.Now.AddSeconds(outPutCache));
}
else
{
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
}
}
}
response.ContentType = GetContentType(contentType);
response.ContentEncoding = System.Text.Encoding.UTF8;
if (data != null)
{
response.Write(data);
}
response.End();
}
总结
现在不管我们前台用什么脚本库,只要按照约定就可以调用标记方法。上面已经介绍了组件的核心部分,您也可以按照自己的想法进行扩展,也欢迎共同学习交流。









