我们可以在不修改原有类型的情况下,为这个类增加新的方法.
一、为内置类型添加扩展方法.
新建一个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();
}
}
}