2011-12-20 69 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 
    } 
} 
相關問題