1.扩展方法2.接口的隐式实现和显式实现
1.扩展方法:必须写在一个静态类里面,具体见代码:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Student s = new Student();
s.HelloWorld("HelloWorld!");
}
}
public class Student
{
void GetName()
{
Console.WriteLine("Tom");
Console.ReadKey();
}
}
public static class StudentEx
{
public static void HelloWorld(this Student self,string str)
{
Console.WriteLine(str);
Console.ReadKey();
}
}
}
在这个例子中,扩展方法写在了StudentEx中,因为HelloWorld这个函数的第一个参数是“this Student self”,即对应的类型是Student,所以在Main函数中才可以对Student实例化后调用HelloWorld方法。如果把HelloWorld的第一个参数类型改为“this Object self”,由于object是所有类的父类,所以所有类的方法都可以使用这个方法。
注:为什么可以这样做,主要是来源于静态方法和非静态方法的区别,非静态方法在编译的时候,编译器会给它加一个参数作为第一个参数,这个参数就是this,这也正是我们在函数体内可以使用this的原因,而静态方法并不会加上this,所以它没办法通过实例化后的对象来调用。扩展方法正是给静态方法加了一个this的参数,使得它可以通过实例化访问。
2.接口的隐式实现和显示实现的区别。
在这篇博文里面说的很清楚,参见http://www.cnblogs.com/chenxizhang/archive/2008/08/22/1274265.html
自己总结一下:通过显式实现的好处是,不把具体类暴露给用户,只暴露接口。
浙公网安备 33010602011771号