原则:
1、扩展方法是一个补丁的概念,在一个进程(一个程序集)的范围内,给某个类型临时加上方法。
所以扩展方法不能写在嵌套类,应该在程序集的全局区,这个程序集的顶级类中。
而且要求有二(在static类中,是一个static方法),this是它和一般的方法的区别符
2、扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。
3、两种使用方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodTest
{
class Program
{
static void Main(string[] args)
{
string str = "abc";
int count = 123;
Person p = new Person("xiaoming");
str.fun();
ExtensionClass.fun(str);
count.fun();
ExtensionClass.fun(count);
p.fun();
ExtensionClass.fun(p);
Console.Read();
}
}
class Person
{
string name;
public Person(string name)
{
this.name = name;
}
public override string ToString()
{
return this.name;
}
}
static class ExtensionClass
{
public static void fun(this string str)
{
Console.WriteLine("this is a extension method with a string parameter:"+str);
}
public static void fun(this int i)
{
Console.WriteLine("this is a extension method with a int parameter:"+i);
}
public static void fun(this Person p)
{
Console.WriteLine("this is a extension method with a int parameter:" + p.ToString());
}
}
}
使用s.fun();这种形式调用,更能体现扩展的意味
使用ExtendMethod.fun(s);这种形式调用,则更能体现扩展方法实现的本质,便于理解为什么是只能访问锁扩展类型的public成员。
至于顶级类中、static类、static方法的规定,这是设计如此,应用在个程序集的范围中,添加新的设计,当然可以在一个类的范围内实现临时扩展,技术上是可行的只是意义不大。
LINQ的实现正是基于扩展方法,实现原理为:
在一个基类上进行扩展,一般而言扩展方法单独地建立一个命名空间,在使用的时候,导入这个命名空间,则开启了扩展方法的可见性,这个时候,所有子类便可以使用这个扩展方法了(因为子类继承了基类,public,static这样的权限级别更是很容易的满足直接调用)
本文详细介绍了C#扩展方法的使用原则、调用方式及其实现原理,包括其在程序集中、static类和static方法中的应用。通过示例展示了如何在不同类型的参数上调用扩展方法,并解释了其与面向对象封装的关系。
1473

被折叠的 条评论
为什么被折叠?



