概念:用来扩展已定义类型中的方法成员的一种方法。
用途:如果想为一个已有类型自定义含有特殊逻辑的新方法时,不想通过重新定义一个类型来继承已有类型的方式去添加该方法,另外当已有类型为值类型或密封类(不能被继承的类)等也不能被继承时,我们可以使用扩展方法来解决。
示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example_ExtenFunc
{
using CustomNamespace;
public class Person
{
public string Name
{
get;
set;
}
}
public static class Extensionclass
{
//扩展方法定义
public static void Print( this Person per )
{
Console.WriteLine( "调用的是当前命名空间下的扩展方法输出,姓名: {0}", per.Name );
}
}
class Program
{
static void Main( string[ ] args )
{
Person p = new Person
{
Name = "Andy"
};
p.Print();
p.Print( "hello" );
Console.Read( );
}
}
}
namespace CustomNamespace
{
using Example_ExtenFunc;
public static class CustomExtensionClass
{
//扩展方法定义
public static void Print( this Person per )
{
Console.WriteLine( "调用的是CustomNamespace命名空间下的扩展方法输出,姓名: {0}", per.Name );
}
public static void Print( this Person per, string s )
{
Console.WriteLine( "调用的是CustomNamespace命名空间下的扩展方法输出,姓名: {0}, 附加字符串{1}", per.Name, s );
}
}
}
运行结果:
扩展方法的定义规则:
(1).扩展方法必须在一个非嵌套、非泛型的静态类中定义
(2).它至少要有一个参数
(3).第一个参数必须加上this关键字作为前缀(第一个参数类型也称为扩展类型,即指方法对这个类型进行扩展)
(4).第一个参数不能使用任何其他的修饰符(如ref、out等修饰符)
(5).第一个参数类型不能是指针类型
编译器调用扩展方法的顺序:
类型的实例方法——> 当前命名空间下的扩展方法——>导入命名空间下的扩展方法。
注意:
(1).如果扩展的类型中定义了无参数的Print实例方法,则编译器不能只能提示给出扩展方法。
(2).如果同一个命名空间下的两个类中含有扩展类型相同的方法,编译器将不知道调用哪个方法,出现编译错误。
(3).空引用也可调用扩展方法。