2011-12-20 67 views
0

在.net 3.5及更低版本中是否存在与MvcHtmlString等效的方法?我已经Google搜索并没有找到答案。我为使用MvcHtmlString的MVC 3/.NET 4创建了一个帮助器。但是它只能在.NET 4上运行。我想编写一个帮助程序的版本,以便它可以在Mvc 2/.net 3.5上运行,这样我可以在使用此运行时的另一个项目上使用帮助程序。我会只使用stringbuilder并返回Stringbuilder.ToString?在.net 3.5及更低版本中的MvcHtmlString相当于?

回答

3

MvcHtmlString可以在.NET 3.5和.NET 4上运行 - 它有一个静态的Create()方法可以用来创建一个新的实例。

静态工厂方法的原因是,可以使用运行时检查来确定环境是否为.NET 4或.NET 3.5;如果环境是.NET 4,则在运行时声明一个新类型,该类型从MvcHtmlString派生并实现IHtmlString,以便使用编码语法编写新的<%: %>响应。

此源代码看起来像(取自MVC 2的源代码)

// in .NET 4, we dynamically create a type that subclasses MvcHtmlString and implements IHtmlString 
private static MvcHtmlStringCreator GetCreator() 
{ 
    Type iHtmlStringType = typeof(HttpContext).Assembly.GetType("System.Web.IHtmlString"); 
    if (iHtmlStringType != null) 
    { 
     // first, create the dynamic type 
     Type dynamicType = DynamicTypeGenerator.GenerateType("DynamicMvcHtmlString", typeof(MvcHtmlString), new Type[] { iHtmlStringType }); 

     // then, create the delegate to instantiate the dynamic type 
     ParameterExpression valueParamExpr = Expression.Parameter(typeof(string), "value"); 
     NewExpression newObjExpr = Expression.New(dynamicType.GetConstructor(new Type[] { typeof(string) }), valueParamExpr); 
     Expression<MvcHtmlStringCreator> lambdaExpr = Expression.Lambda<MvcHtmlStringCreator>(newObjExpr, valueParamExpr); 
     return lambdaExpr.Compile(); 
    } 
    else 
    { 
     // disabling 0618 allows us to call the MvcHtmlString() constructor 
#pragma warning disable 0618 
     return value => new MvcHtmlString(value); 
#pragma warning restore 0618 
    } 
} 
相关问题