C#之扩展方法

我们可以在不修改原有类型的情况下,为这个类增加新的方法.

一、为内置类型添加扩展方法.

新建一个AddMethods类:

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

namespace ConsoleApplication1
{
    public static class AddMethods
    {
        public static void LogNumAdd (this int num, int addNum)
        {
            Console.WriteLine(num + addNum);
        }
    }
}

注意,扩展方法必须是在非泛型静态类中定义的静态方法.同时第一个参数必须是this + 要增加扩展方法的类型 + 形参,代表调用对象;后面可根据需要添加参数.

调用方式有两种:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 100;
            num.LogNumAdd(200);

            AddMethods.LogNumAdd(123, 100);
        }
    }
}

1.通过对应类型的对象调用.

2.通过静态类调用.结果相同.

二、为自定义类型添加扩展.

定义一个Person类:

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

namespace ConsoleApplication1
{
    class Person
    {
        public Person (int age)
        {
            this.age = age;
        }

        public int age;
    }
}

为Person类添加扩展方法:

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

namespace ConsoleApplication1
{
    static class AddMethods
    {
        public static void LogPersonAge (this Person person)
        {
            Console.WriteLine(person.age);
        }
    }
}

测试:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person(18);
            p.LogPersonAge();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值