C#学习笔记(三)—–C#高级特性:扩展方法

来源:互联网 发布:md5摘要算法 编辑:程序博客网 时间:2024/05/28 05:17

C#高级特性:扩展方法

  • 扩展方法允许为一个类定义新的方法但是不用操作这个类。扩展方法就是一个静态类的静态方法,这个方法的第一个参数的类型就是要扩展的这个类的类型(加this):
public static class StringHelper{public static bool IsCapitalized (this string s){if (string.IsNullOrEmpty(s)) return false;return char.IsUpper (s[0]);}}

IsCapitalized方法像实例方法一样被string来调用,像这样:

Console.WriteLine ("Perth".IsCapitalized());

扩展方法被编译后会被编译器转换为普通的静态类的静态方法的调用,像这样:

Console.WriteLine (StringHelper.IsCapitalized ("Perth"));

这个转换过程如下:

arg0.Method (arg1, arg2, ...); // 扩展方法的调用StaticClass.Method (arg0, arg1, arg2, ...); // 编译器将它转换成静态方法调用

接口也可以一样的进行扩展:

public static T First<T> (this IEnumerable<T> sequence){foreach (T element in sequence)return element;throw new InvalidOperationException ("No elements!");}...Console.WriteLine ("Seattle".First()); // S

扩展方法在c#3.0引入。

扩展方法链

扩展方法像实例方法一样,支持整洁的链式的函数调用,考虑下面的两个函数:

public static class StringHelper{public static string Pluralize (this string s) {...}public static string Capitalize (this string s) {...}}string x = "sausage".Pluralize().Capitalize();string y = StringHelper.Capitalize (StringHelper.Pluralize ("sausage"));

x和y的结果是一样的,只不过x是使用的实例方法的方式进行调用,y使用的是静态方法进行调用。

多义性和解析

  • 命名空间:除非在一个命名空间内(或利用using引入命名空间),否则我们不能访问扩展方法,考虑下面的IsCapitalized方法:
using System;namespace Utils{public static class StringHelper{public static bool IsCapitalized (this string s){if (string.IsNullOrEmpty(s)) return false;return char.IsUpper (s[0]);}}}

如果要使用IsCapitalized,那么下面的程序必须导入Utils命名空间,因为这个方法在Utils命名空间中定义。否则会出现编译错误。

namespace MyApp{using Utils;class Test{static void Main(){Console.WriteLine ("Perth".IsCapitalized());}}}
  • 扩展方法和实例方法:任何兼容的实例方法总是优先于扩展方法调用,在下面的例子中,即使输入一个参数类型为int的参数,也会优先调用Test类中的Foo:
class Test{public void Foo (object x) { } // This method always wins}static class Extensions{public static void Foo (this Test t, int x) { }}
  • 扩展方法和扩展方法:如果两个扩展方法名称相同,那么扩展方法必须作为静态方法来调用以加以区别,如果其中一个扩展方法的参数类型更具体,那么这个方法被优先调用,例如下面这两个类:
static class StringHelper{public static bool IsCapitalized (this string s) {...}}static class ObjectHelper{public static bool IsCapitalized (this object s) {...}}

下面的代码调用的是StringHelper的扩展方法:

bool test1 = "Perth".IsCapitalized();

如果要调用ObjectHelper的扩展方法,我们必须显示的去调用:

bool test2 = (ObjectHelper.IsCapitalized ("Perth"));
阅读全文
0 0