开发者

.NET 4 function : Function argument question

I'm following a tutorial on MVC on the .NET 4 framework. The tutorial created a function like this...

using System.Web;
using System.Web.Mvc;

namespace vohministries.Helpers
{
开发者_开发百科    public static class HtmlHelpers
    {
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }
    }
}

I have no idea whatthis HtmlHelper helper means or represents in the function argument. Is this something new in .NET 4? I think it may be extending the HtmlHelper class but I'm not sure...Could someone explain the syntax?


It's an extension method. (Been in since C# 3.0):

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.


You can call that extension method in two ways:

HtmlHelpers.Truncate(helper, input, length)

OR

helper.Truncate(input, length)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜