C# 泛型自定义集合

我就是我 2022-06-06 03:45 310阅读 0赞

一.原型

  1. public class InList {
  2. int[] arr = new int[10];
  3. int index = 0;
  4. public void Add(int param)
  5. {
  6. if (index >= arr.Length)
  7. {
  8. int[] tmp = new int[arr.Length * 2];
  9. arr.CopyTo(tmp, 0);
  10. arr = tmp;
  11. }
  12. arr[index] = param;
  13. index++;
  14. }
  15. public int this[int index]
  16. {
  17. get
  18. {
  19. if (index >= arr.Length)
  20. {
  21. throw new Exception("索引越界");
  22. }
  23. return arr[index];
  24. }
  25. }
  26. }

二.泛型自定义集合

  1. /// <summary>
  2. /// 自定义泛型类集合
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. public class MyList<T>
  6. {
  7. T[] arr = new T[10];
  8. int index = 0;
  9. public void Add(T param)
  10. {
  11. if (index >= arr.Length)
  12. {
  13. T[] tmp = new T[arr.Length * 2];
  14. arr.CopyTo(tmp, 0);
  15. arr = tmp;
  16. }
  17. arr[index] = param;
  18. index++;
  19. }
  20. public T this[int index]
  21. {
  22. get
  23. {
  24. if (index >= arr.Length)
  25. {
  26. throw new Exception("索引越界");
  27. }
  28. return arr[index];
  29. }
  30. }
  31. }

调用

  1. class Program {
  2. static void Main(string[] args)
  3. {
  4. //InList ilist = new InList();
  5. //ilist.Add(1);
  6. //ilist.Add(3);
  7. //ilist.Add(4);
  8. //ilist.Add(7);
  9. //Console.WriteLine(ilist[3]);
  10. //Console.ReadKey();
  11. MyList<int> ilist = new MyList<int>();
  12. ilist.Add(1);
  13. MyList<string> sList = new MyList<string>();
  14. sList.Add("1");
  15. //MyList1.MyList`1[System.String]
  16. Console.WriteLine(sList.ToString());
  17. Console.ReadKey();
  18. }
  19. }

发表评论

表情:
评论列表 (有 0 条评论,310人围观)

还没有评论,来说两句吧...

相关阅读

    相关 java 定义

    Java泛型编程是JDK1.5版本后引入的! 一.泛型的优点 (1)类型安全 通过知道使用泛型定义的变量的类型限制,编译器可以更有效地提高Java程序的类型安全。 (2

    相关 java定义T

      在编译过程中,对于正确检验泛型结果后,会将泛型的相关信息擦出,也就是说,成功编译过后的class文件中是不包含任何泛型信息的。泛型信息不会进入到运行时阶段。 1.泛型类

    相关 定义—java

    自定义泛型 1 当实例化泛型类的对象时,指明泛型类的类型。指明之后,对应的类中所有使用泛型的位置,都变为实例化中指定的泛型的类型 2 如果我们自定义了泛型类,但是在实例化时