首页 > 技术文章 > C# 扩展方法

wrbxdj 2016-07-18 10:24 原文

扩展方法就是为一个现有类型添加一个方法,现有类型既可以是int,string等数据类型,也可以是自定义的数据类型。

扩展方法存在与静态类中,是一个静态方法。

格式:

访问修饰服 static class 类名
{
    访问修饰服 static 返回值类型 方法名(this 所扩展类型 扩展类型对象, 参数列表)
    {
        ...
    }
}

一个静态类中可以有多个扩展方法。

我们在一个类中实现两个扩展方法,分别对类型string 和类型 int 进行扩展。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ch14_
{
    static class expand
    {
        public static void print(this string str, string describe = "describe")
        {
            Console.WriteLine(describe + ": " + str);
        }
        public static void print(this int iVal, string describe = "describe")
        {
            Console.WriteLine(describe + ": " + iVal);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Mical";
            name.print("三班1号");
            int score = 620;
            score.print("总成绩");
        }
    }
}

结果:

三班1号: Mical
总成绩: 620

 

推荐阅读