这是MVC3中的扩展或帮助方法吗?

时间:2011-11-18 06:34:33

标签: c# asp.net-mvc asp.net-mvc-3

我很困惑哪个是哪个。有人可以解释两者之间的区别。

例如以下是返回MvcHtmlString的扩展名还是辅助方法?

public static class LinkExtensions
{
    public static MvcHtmlString HdrLinks(
        this HtmlHelper helper, 
        string topLink, 
        string subLink, 
        System.Security.Principal.IPrincipal user)
    {
    etc ...

这个怎么样:

    public static class Slug
{
    public static string Generate(string phrase, int maxLength = 50)
    {
        string str = RemoveAccent(phrase).ToLower();
        str = Regex.Replace(str, @"[^a-z0-9\s-]", " ");
        str = Regex.Replace(str, @"[\s-]+", " ").Trim();
        str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim();
        str = Regex.Replace(str, @"\s", "-");
        return str;
    }

2 个答案:

答案 0 :(得分:4)

它们不是辅助方法,它们被称为HTML帮助程序。在C#中没有“辅助方法”实现。 HTML帮助程序实现为扩展方法。您可以在第一个参数之前看到扩展方法是带有此子句的静态方法。 HTML帮助程序可以更轻松地生成html标记。

答案 1 :(得分:0)

public static MvcHtmlString HdrLinks(this HtmlHelper helper, string topLink)

既是C#扩展方法,也是ASP.NET MCV视图中使用的html帮助方法:

//Example of a call as an extension method:

var helper = new HtmlHelper(...);
var result = helper.HdrLinks(topLink);

//Example of a call as a helper method in an MVC razor view:
@Html.HdrLinks(topLink)

以下是“标准”静态C#方法:

public static class Slug {
  public static string Generate(string phrase, int maxLength = 50)
}

//Example of call:

var phrase = "Freech Alpes are the surfer's best spot"
var result = Slug.Generate(phrase);

在没有类实例的情况下调用静态方法。它是一个特殊的虚拟构造,用于对函数进行分组。