.Net 3.5及更低版本中是否有与MvcHtmlString等效的方法?我用Google搜索并没有找到答案。我为MVC 3 / .NET 4创建了一个使用MvcHtmlString的帮助器。但是它只能在.NET 4上运行。我想编写一个帮助程序的版本,以便它可以在Mvc 2 / .net 3.5上运行,这样我就可以在另一个使用这个运行时的项目上使用帮助程序。我会使用stringbuilder并返回Stringbuilder.ToString吗?
答案 0 :(得分: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
}
}