Presentation is loading. Please wait.

Presentation is loading. Please wait.

泛型委托 泛型接口、方法和委托.

Similar presentations


Presentation on theme: "泛型委托 泛型接口、方法和委托."— Presentation transcript:

1 泛型委托 泛型接口、方法和委托

2 泛型委托 委托(Delegate)回顾 类似于C/C++中的函数指针 采用面向对象的方法来封装方法(子程序)
delegate double Func(double x); Func f1 = new Func(Math.Log); double y = f1(0.5); //double y = Math.Log(0.5); f1 = new Func(Math.Sqrt); y = f1(10); //y = Math.Sqrt(10); Func[] fs = new Func[]{Math.Log, Math.Sin, Math.Cos, Math.Tan); foreach(Func f in fs) Console.WriteLine(f(0.5));

3 泛型委托 定义 使用 delegate T Func(T x, T y) where T: IComparable;
Func<int> f1 = new Func(Math.Max<int>); int x = f1(5, 7); Func<double> f2 = new Func(Math.Max<double>); double y = f2(0.5, 0.7); f2 = new Func(Math.Power); double z = f1(x,y);

4 泛型委托 封装命名方法 Demo

5 泛型委托 高级用法 封装匿名方法 delegate T Func(T x);
Func f1 = delegate(int x) {return x*x;}; int x = f1(5); Func f1 = delegate {return 10;}; x = f1(7); f1 = delegate(int x) {int y=x; while(x>1) y*=(--x); return y;};

6 泛型委托 封装匿名方法 Demo

7 泛型委托 高级用法 封装匿名方法 封装Lambda表达式(C#3.0特性) delegate T Func(T x);
Func f1 = (int x) ==> x*x; Func<int> f1 = x ==> x*x; int y = 1; f1 = x ==> (x>1) ==> y*=(x--);

8 泛型委托 高级用法 封装匿名方法 封装Lambda表达式(C#3.0特性) LINQ查询(C#3.0特性)
public static IEnumerable<T> Where<T>( this IEnumerable<T> source, Func<T, bool> predicate); public static IEnumerable<S> Select<T, S>( this IEnumerable<T> source, Func<T, S> selector); var expr = customers .Where(c => c.Country == Countries.Italy) .Select(c => c.Name);

9 $12 遍历器 C#泛型程序设计

10 遍历器 tCollection: 类型实现IEnumerable/ Ienumerable<T>
int[] iArray = new int[]{1,3,5,7,9}; foreach(int i in iArray) Console.WriteLine(2*i+1); List<Student> students = new List<Student>(); Students.Add(new Student()); foreach(Student s in students) Console.WriteLine(s.Name); foreach(T t in tCollection); Console.WriteLine(t); tCollection: 类型实现IEnumerable/ Ienumerable<T>

11 遍历器 public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerable<T> : IEnumerable IEnumerator<T> GetEnumerator();

12 IEnumerable<Student>
遍历器 foreach(Student s in students) Console.WriteLine(s.Name); IEnumerable<Student> GetEnumerator() IEnumerator<Student> MoveNext():true MoveNext():true yield return Before Running Suspending Yield break MoveNext():false After

13 遍历器 自定义枚举器 Demo


Download ppt "泛型委托 泛型接口、方法和委托."

Similar presentations


Ads by Google