C# 高级课题之迭代器,泛型接口和方法

时间:2020-12-24 19:24:48

呵呵,在C#的程序代码规范中,我想这是高级的技巧了吧。

分部类应该不算。。

现在我只能照书上写简单的代码。

希望以后能更深入的理解,,,

但这必须要有合适的CASE。。。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace WindowsFormsApplication1
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         private void Form1_Load(object sender, EventArgs e)
21         {
22             Family myfamily = new Family();
23 
24             foreach (string str in myfamily)
25             {
26                 richTextBox1.Text += str + "\n";
27             }
28         }
29     }
30     public class Family : System.Collections.IEnumerable
31     {
32         string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹", "姐姐" };
33         public System.Collections.IEnumerator GetEnumerator()
34         {
35             for (int i = 0; i < MyFamily.Length; i++)
36             {
37                 yield return MyFamily[i];
38             }
39         }
40     }
41 }

C# 高级课题之迭代器,泛型接口和方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     public interface IGenericInterface<T>
10     {
11         T CreateInstance();
12     }
13     public class Factory<T, T1> : IGenericInterface<T1> where T : T1, new()
14     {
15         public T1 CreateInstance()
16         {
17             return new T();
18         }
19     }
20     public class Finder
21     {
22         public static int Find<T>(T[] items, T item)
23         {
24             for (int i = 0; i < items.Length; i++)
25             {
26                 if (items[i].Equals(item))
27                 {
28                     return i;
29                 }
30             }
31             return -1;
32         }
33     }
34     class Program
35     {
36         static void Main(string[] args)
37         {
38             IGenericInterface<System.ComponentModel.IListSource> factory =
39                 new Factory<System.Data.DataTable, System.ComponentModel.IListSource>();
40             Console.WriteLine(factory.CreateInstance().GetType().ToString());
41             Console.WriteLine();
42             int i = Finder.Find<int>(new int[] {1,2,3,4,5,6,7,8,9,10,11,12}, 8);
43             Console.WriteLine("8在数组中的位置: " + i.ToString());
44             Console.ReadLine();
45         }
46     }
47 }

C# 高级课题之迭代器,泛型接口和方法