【发布时间】:2010-08-26 22:22:55
【问题描述】:
目前,我在实现接口 IOutputCacheVaryByCustom 的类中实现了 VaryByCustom 功能
public interface IOutputCacheVaryByCustom
{
string CacheKey { get; }
HttpContext Context { get; }
}
实现此接口的类有一些约定,类的名称将是“OutputCacheVaryBy_______”,其中空白是从页面上的 varyByCustom 属性传入的值。另一个约定是 Context 将通过构造函数注入来设置。
目前我基于一个枚举和一个类似于
的 switch 语句public override string GetVaryByCustomString(HttpContext context,
string varyByCustomTypeArg)
{
//for a POST request (postback) force to return back a non cached output
if (context.Request.RequestType.Equals("POST"))
{
return "post" + DateTime.Now.Ticks;
}
var varyByCustomType = EnumerationParser.Parse<VaryByCustomType?>
(varyByCustomTypeArg).GetValueOrDefault();
IOutputCacheVaryByCustom varyByCustom;
switch (varyByCustomType)
{
case VaryByCustomType.IsAuthenticated:
varyByCustom = new OutputCacheVaryByIsAuthenticated(context);
break;
case VaryByCustomType.Roles:
varyByCustom = new OutputCacheVaryByRoles(context);
break;
default:
throw new ArgumentOutOfRangeException("varyByCustomTypeArg");
}
return context.Request.Url.Scheme + varyByCustom.CacheKey;
}
由于我一直都知道该类将是 OutputCacheVaryBy + varyByCustomTypeArg 并且唯一的构造函数参数将是 context 我意识到我可以绕过需要这个美化的 if else 块并且可以使用 Activator 实例化我自己的对象。
话虽如此,反射并不是我的强项,我知道Activator 与静态创建和其他生成对象的方式相比要慢得多。有什么理由我应该坚持使用当前的代码还是应该使用Activator 或类似的方式来创建我的对象?
我看过博客 http://www.smelser.net/blog/post/2010/03/05/When-Activator-is-just-to-slow.aspx,但我不确定这将如何应用,因为我在运行时使用类型而不是静态 T。
【问题讨论】:
-
创建对象是否昂贵(耗时)?构建过程中是否需要上下文,是否可以改为通过 Context 属性设置?这些问题的答案是提供最佳解决方案所必需的。
-
没有创建微不足道的对象,并且最好在构造函数中设置上下文,因为这是对类的核心依赖,但是它可以在属性上公开和设置,但这为 NRE 留出了空间。
-
你用的是什么版本的c#?
标签: c# reflection dynamic-class-creation