这是MVC3中的扩展方法还是辅助方法?

本文关键字:方法 这是 扩展 MVC3 | 更新日期: 2023-09-27 18:14:58

我分不清哪个是哪个。有人能解释一下这两者的区别吗?

例如,下面是返回一个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;
    }

这是MVC3中的扩展方法还是辅助方法?

它们不是帮助方法,它们被称为HTML帮助方法。c#中没有"辅助方法"的实现。HTML helper是作为扩展方法实现的。您可以看到扩展方法是静态方法,在第一个参数之前带有this子句。HTML helper使生成HTML标记变得更容易。

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

既是一个c#扩展方法,也是一个在ASP中使用的html helper方法。. NET MCV视图:

//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);
静态方法在没有类实例的情况下调用。