zoukankan      html  css  js  c++  java
  • 扩展方法

    扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

    创建扩展方法的先决条件如下,扩展方法必须定义在一个非嵌套、非泛型的静态类中,扩展方法必须声明为静态,扩展发放至少拥有一个参数(即调用者本身),第一个参数要以 this 关键字作为前缀,在参数列表中不能有其他修饰符(如 ref,out)。

    以下代码展示了如何为 string 类型创建一个扩展方法实现添加尾缀“ing”:

    static class Test
    {
        public static string AddSuffix(this string str, int i)
        {
            return string.Format("{0}ing {1} projects", str, i);
        }
    }

    以下代码定义一个字符串变量,并用其调用新建扩展方法:

    class Program
    {
        static void Main()
        {
            string str = "do";
            string newstr = str.AddSuffix(2);
            Console.WriteLine(newstr);
            Console.ReadKey();
        }
    }

    输出结果如下:

    doing 2 projects
  • 相关阅读:
    ffmpeg
    HDU 1031 Design T-Shirt
    HDU 1029 Ignatius and the Princess IV
    HDU 1022 Train Problem I
    HDU 1017 A Mathematical Curiosity
    HDU 1015 Safecracker
    HDU 1002 A + B Problem II
    HDU 1070 Milk
    高精度算法(一)
    codeblocks 使用心得
  • 原文地址:https://www.cnblogs.com/jizhiqiliao/p/9814967.html
Copyright © 2011-2022 走看看