“this” in function parameter

前端 未结 5 1106
南方客
南方客 2020-12-02 06:36

Looking at some code examples for HtmlHelpers, and I see declarations that look like:

public static string HelperName(this HtmlHelper htmlHelper, ...more reg         


        
5条回答
  •  旧时难觅i
    2020-12-02 07:14

    Extensions Methods...

    ...are a fantastic way to include functionality like if you where using the decorator pattern, but without the pain of refactoring all your code, or using a different name of a common type.

    public static class Extensions
    {
         public static string RemoveComma(this string value)
         {
             if (value == null) throw new ArgumentNullException("value");
            return value.Replace(",", "");
        }
    }  
    

    So you can use this code, anywhere in you app.

    Console.WriteLine(“Hello, My, Friend”.RemoveComma())
    
    >> Hello My Friend
    

    So the this command attribute mean the type that the extension will be “added”, and let you work with the value as if it was passed as parameter.

提交回复
热议问题