FROM P 144
Part1 静态类
静态类中所有成员都是静态的。静态类用于存放不受实例数据影响的数据和函数。静态类的一个常见用途可能就是创建一个包含一组数学方法和值的数学库。
关于静态类需要了解的重要事情如下:
□类本身必须标记为static
□类的所有成员必须是静态的
□类可以有一个静态构造函数,但不能有实例构造函数,不能创建类的实例
□静态类是隐式密封的,也就是说,不能继承静态类。
示例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace review 8 { 9 static public class MyMath //类必须标记为静态的 10 { 11 public static float PI = 3.14f; 12 public static bool IsOdd(int x) //成员必须是静态的 13 { 14 return x % 2 == 1; 15 } 16 public static int Times2(int x) //成员必须是静态的 17 { 18 return 2 * x; 19 } 20 } 21 class Program 22 { 23 static void Main(string[] args) 24 { 25 int val = 3; 26 Console.WriteLine("{0} is odd is {1}.", val, MyMath.IsOdd(val)); 27 Console.WriteLine("{0} * 2 = {1}.", val, MyMath.Times2(val)); 28 Console.Read(); 29 } 30 } 31 } 32 /* 33 * 输出如下: 34 * 3 is odd is true. 35 * 3 * 2 = 6. 36 * */
Part2 扩展方法
迄今为止,每个方法都和声明它的类关联。扩展方法特性扩展了这个边界,允许编写的方法和声明它的类之外的类关联。
其要求有:
□声明扩展方法的类必须声明为static
□扩展方法本身必须声明为static(实际上,根据上述静态类的描述,静态类不能有非静态方法)
□扩展方法必须包含关键字this作为它的第一个参数类型,并在后面跟着它所扩展的类的名称
其基本结构如下:(以声明类 Mydata的扩展 average方法为例)
以下为一个具体示例,注意方法Average完全如同它是MyData的实例成员那样调用。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace review 8 { 9 sealed class MyData 10 { 11 private double D1, D2, D3; 12 public MyData(double d1,double d2,double d3) 13 { 14 D1 = d1;D2 = d2;D3 = d3; 15 } 16 public double sum() { return D1 + D2 + D3; } 17 } 18 static class ExtendMyData 19 { 20 public static double Average(this MyData md) //声明为静态的,加上关键字和类型 21 { 22 return md.sum() / 3; 23 } 24 } 25 class Program 26 { 27 static void Main(string[] args) 28 { 29 MyData md = new MyData(3, 4, 5); 30 Console.WriteLine("Sum: {0}", md.sum()); 31 Console.WriteLine("Average: {0}", md.Average());//当作类的实例成员来调用 32 Console.Read(); 33 } 34 } 35 } 36 /* 37 * 输出如下: 38 * Sum: 12 39 * Average: 4 40 * */