• C# Extension Methods


    In C#, extension methods enable you to add methods to existing class without creating a new derived class.

    Extension methods 要求:

    1. Define a static class to contain extension method. This class must be visible to client code.
    2. Implement the extension method like a static method, but add "this" modifier before the first parameter.
    3. The first parameter specifies the type that this extension method operates on.
     1 using System.Globalization;
     2 using System.Threading;
     3 
     4 namespace Library
     5 {
     6     public static class StringExtensions
     7     {
     8         //static method
     9         //public static string ConvertToTitleCase(this string source)
    10         //extension method
    11         public static string ConvertToTitleCase(this string source)
    12         {
    13             CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    14             TextInfo textInfo = cultureInfo.TextInfo;
    15 
    16             return textInfo.ToTitleCase(source);
    17         }
    18     }
    19 }

    Extension methods call:

     Call extension method  like extension method is an instance method on the type.

     1 namespace Library_Simple
     2 {
     3     //Import extension method namespace
     4     using Library;
     5     class Program
     6     {
     7         static void Main(String[] args)
     8         {
     9             string source = "the return of the king";
    10             string extected = "The Return Of The King";
    11 
    12             //static method
    13             //string result = StringExtensions.ConvertToTitleCase(source);
    14             //extension method
    15             string result = source.ConvertToTitleCase();
    16 
    17             Assert.IsNotNull(result);
    18             Assert.AreEqual(expected, result);
    19         }
    20     }
    21 }
  • 相关阅读:
    hibernate关联关系映射
    java单例模式
    HTML如何给table添加滚动条
    jquery的几种ajax方式对比
    JQuery Selectors 方法说明
    jQuery遍历对象/数组/集合
    Jquery常用函数
    【刷题】【省选】ZJOI2017_仙人掌_LOJ2250/Luogu3687_圆方树/dp计数/树形dp
    【学习笔记】圆方树学习笔记
    【模板】【刷题】差分与前缀和_LuoguP5488_多项式
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5958925.html
Copyright © 2020-2023  润新知