C# 核心语法-扩展方法

using System;

 

namespace lesson9_拓展方法

{

    #region 拓展方法基本概念

    //概念

    //为现有非静态 变量类型 添加 新方法

    //作用

    //1.提升程序拓展性

    //2.不需要在对象中重新写方法

    //3.不需要继承来添加方法

    //4.为别人封装的类型写额外的方法

    //特点

    //1.一定是写在静态类中

    //2.一定是个静态函数

    //3.第一个参数为拓展目标

    //4.第一个参数用this修饰

    #endregion

 

    #region 基本语法

    //访问修饰符 static 返回值 函数名(this 拓展类名 参数名,参数类型 参数名,参数类型 参数名……)

    #endregion

 

    #region 实例

    static class Tools

    {

        //为int拓展了一个成员方法

        //成员方法 是需要 实例化对象后 才能使用的

        //value 代表 使用该方法的 实例化对象

        public static void SpeakValue(this int value)

        {

            //拓展方法的逻辑

            Console.WriteLine("为int拓展的方法" + value);

        }

        public static void SpeakStringInfo(this string str, string str2, string str3)

        {

            Console.WriteLine("为string拓展的方法");

            Console.WriteLine("调用方法的对象" + str);

            Console.WriteLine("传的参数" + str2+str3);

        }

 

        public static void Fun3(this Test t)

        {

            Console.WriteLine("为Test拓展的方法");

        }

    }

    #endregion

 

    #region 为自定义的类型拓展方法

    class Test

    {

        public int i = 10;

 

        public void Fun()

        {

            Console.WriteLine("123");

        }

        public void Fun2()

        {

            Console.WriteLine("456");

        }

    }

    #endregion

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("拓展方法");

 

            #region 使用

            int i = 10;

            i.SpeakValue();

 

            string str = "000";

            str.SpeakStringInfo("于双", "222");

 

            Test t = new Test();

            t.Fun3();

            #endregion

        }

    }

    //总结

    //概念:为现有的非静态类 变量类型 添加 方法

    //作用:

    //提升程序拓展性

    //不需要在对象中重新写方法

    //不需要继承来添加方法

    //为别人封装的类型写额外的方法

 

    //特点

    //静态类中的静态方法

    //第一个参数为拓展目标

    //第一个参数用this修饰

    

    //注意

    //可以有返回值和n个参数

    //根据需求而定

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值