泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用在集合和在集合上运行的方法中。.NET Framework 2.0 版类库提供一个新的命名空间 System.Collections.Generic,其中包含几个新的基于泛型的集合类。建议面向 2.0 版的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类,如 ArrayList。有关更多信息,请参见 .NET Framework 类库中的泛型(C# 编程指南)

当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类。(大多数情况下,建议使用 .NET Framework 类库提供的 List<T> 类,而不要自行创建类。)在通常使用具体类型来指示列表中所存储项的类型时,可使用类型参数 T。其使用方法如下:

  • 在 AddHead 方法中作为方法参数的类型。

  • 在 Node 嵌套类中作为公共方法 GetNext 和 Data 属性的返回类型。

  • 在嵌套类中作为私有成员数据的类型。

注意,T 可用于 Node 嵌套类。如果使用具体类型实例化 GenericList<T>(例如,作为 GenericList<int>),则所有的 T 都将被替换为 int。

 
  1. // type parameter T in angle brackets
  2. public class GenericList<T>
  3. {
  4. // The nested class is also generic on T
  5. private class Node
  6. {
  7. // T used in non-generic constructor
  8. public Node(T t)
  9. {
  10. next = null;
  11. data = t;
  12. }
  13.  
  14. private Node next;
  15. public Node Next
  16. {
  17. get { return next; }
  18. set { next = value; }
  19. }
  20.  
  21. // T as private member data type
  22. private T data;
  23.  
  24. // T as return type of property
  25. public T Data
  26. {
  27. get { return data; }
  28. set { data = value; }
  29. }
  30. }
  31.  
  32. private Node head;
  33.  
  34. // constructor
  35. public GenericList()
  36. {
  37. head = null;
  38. }
  39.  
  40. // T as method parameter type:
  41. public void AddHead(T t)
  42. {
  43. Node n = new Node(t);
  44. n.Next = head;
  45. head = n;
  46. }
  47.  
  48. public IEnumerator<T> GetEnumerator()
  49. {
  50. Node current = head;
  51.  
  52. while (current != null)
  53. {
  54. yield return current.Data;
  55. current = current.Next;
  56. }
  57. }
  58. }

下面的代码示例演示客户端代码如何使用泛型 GenericList<T> 类来创建整数列表。只需更改类型参数,即可方便地修改下面的代码示例,创建字符串或任何其他自定义类型的列表:

 
  1. class TestGenericList
  2. {
  3. static void Main()
  4. {
  5. // int is the type argument
  6. GenericList<int> list = new GenericList<int>();
  7.  
  8. for (int x = 0; x < 10; x++)
  9. {
  10. list.AddHead(x);
  11. }
  12.  
  13. foreach (int i in list)
  14. {
  15. System.Console.Write(i + " ");
  16. }
  17. System.Console.WriteLine("\nDone");
  18. }
  19. }

在泛型类和泛型方法中产生的一个问题是,在预先未知以下情况时,如何将默认值分配给参数化类型 T:

  • T 是引用类型还是值类型。

  • 如果 T 为值类型,则它是数值还是结构。

给定参数化类型 T 的一个变量 t,只有当 T 为引用类型时,语句 t = null 才有效;只有当 T 为数值类型而不是结构时,语句 t = 0 才能正常使用。 解决方案是使用 default 关键字,此关键字对于引用类型会返回 null,对于数值类型会返回零。 对于结构,此关键字将返回初始化为零或 null 的每个结构成员,具体取决于这些结构是值类型还是引用类型。 对于可以为 null 的值类型,默认返回 System.Nullable(Of T),它像任何结构一样初始化。

  1.  
  2. namespace ConsoleApplication1
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             // Test with a non-empty list of integers.
  9.             GenericList<int> gll = new GenericList<int>();
  10.             gll.AddNode(5);
  11.             gll.AddNode(4);
  12.             gll.AddNode(3);
  13.             int intVal = gll.GetLast();
  14.             // The following line displays 5.
  15.             System.Console.WriteLine(intVal);
  16.  
  17.             // Test with an empty list of integers.
  18.             GenericList<int> gll2 = new GenericList<int>();
  19.             intVal = gll2.GetLast();
  20.             // The following line displays 0.
  21.             System.Console.WriteLine(intVal);
  22.  
  23.             // Test with a non-empty list of strings.
  24.             GenericList<string> gll3 = new GenericList<string>();
  25.             gll3.AddNode("five");
  26.             gll3.AddNode("four");
  27.             string sVal = gll3.GetLast();
  28.             // The following line displays five.
  29.             System.Console.WriteLine(sVal);
  30.  
  31.             // Test with an empty list of strings.
  32.             GenericList<string> gll4 = new GenericList<string>();
  33.             sVal = gll4.GetLast();
  34.             // The following line displays a blank line.
  35.             System.Console.WriteLine(sVal);
  36.         }
  37.     }
  38.  
  39.     // T is the type of data stored in a particular instance of GenericList.
  40.     public class GenericList<T>
  41.     {
  42.         private class Node
  43.         {
  44.             // Each node has a reference to the next node in the list.
  45.             public Node Next;
  46.             // Each node holds a value of type T.
  47.             public T Data;
  48.         }
  49.  
  50.         // The list is initially empty.
  51.         private Node head = null;
  52.  
  53.         // Add a node at the beginning of the list with t as its data value.
  54.         public void AddNode(T t)
  55.         {
  56.             Node newNode = new Node();
  57.             newNode.Next = head;
  58.             newNode.Data = t;
  59.             head = newNode;
  60.         }
  61.  
  62.         // The following method returns the data value stored in the last node in
  63.         // the list. If the list is empty, the default value for type T is
  64.         // returned.
  65.         public T GetLast()
  66.         {
  67.             // The value of temp is returned as the value of the method. 
  68.             // The following declaration initializes temp to the appropriate 
  69.             // default value for type T. The default value is returned if the 
  70.             // list is empty.
  71.             T temp = default(T);
  72.  
  73.             Node current = head;
  74.             while (current != null)
  75.             {
  76.                 temp = current.Data;
  77.                 current = current.Next;
  78.             }
  79.             return temp;
  80.         }
  81.     }

}

c# T obj = default(T);的更多相关文章

  1. c#webservice的简单示例

    webservice.就概念上来说,可能比较复杂,不过我们可以有个宏观的了解:webservice就是个对外的接口,里面有 函数可供外部客户调用(注意:里面同样有客户不可调用的函数).假若我们是服务端 ...

  2. go、java or c艹 引用的本质

    在底层,引用变量由指针按照指针常量的方式实现 即一个指针常量,和一些解引用等的封装: 合到一起实现了指针这么一种形式. 用指针和引用编译到了汇编层面应该是一样的.

  3. C#+ AE 注意问题汇总(不断更新)

    1.AE的COM对象释放问题尤其是IFeatureCursor 建议用 ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(pObj); 或者 int iRefs ...

  4. C# 日文网址转punnycode

    Uri uri = new Uri(url); IdnMapping idn = new IdnMapping();url= url.Replace(uri.Host, idn.GetAscii(ur ...

  5. 如何将外部的obj模型导入OpenGL

    1.关于obj的说明. obj中存放的是顶点坐标信息(v),面的信息(f),法线(vn),纹理坐标(vt),以及材质(这个放在mtl)中 我使用CINEMA 4D导出用VS查看后的信息: CINEMA ...

  6. OpenGL OBJ模型加载.

    在我们前面绘制一个屋,我们可以看到,需要每个立方体一个一个的自己来推并且还要处理位置信息.代码量大并且要时间.现在我们通过加载模型文件的方法来生成模型文件,比较流行的3D模型文件有OBJ,FBX,da ...

  7. SQL Server 默认跟踪(Default Trace)

    一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 基础知识(Rudimentary Knowledge) 查看默认跟踪信息(Default Tr ...

  8. $(obj).data() 绑定和获取数据的应用

    1.解说 data() 方法向被选元素附加数据,或者从被选元素获取数据. 例如:$("#id").data("name","xiao"); ...

  9. 构造函数语义学之Default Constructor构建操作

    一.Default Constructor的构建操作 首先大家要走出两个误区: 1).任何class如果没有定义default constructor,就会被合成一个来. 2).便以其合成出来的def ...

随机推荐

  1. 编译是报error: 'EVNET_COME_TO_FOREGROUND' was not declared in this scope

    Compile++ thumb  : game_shared <= main.cpp jni/hellocpp/main.cpp: In function 'void Java_org_coco ...

  2. python(28)获得网卡的IP地址,如何在其他文件夹中导入python模块

    获得第几块网卡的ip地址: 如何在其他文件夹中导入模块 import sys sys.path.append('/search/chen/tool')#你的代码存放的目录 from Get_Ip im ...

  3. nyoj592 spiral grid

    spiral grid 时间限制:2000 ms  |  内存限制:65535 KB 难度:4   描述 Xiaod has recently discovered the grid named &q ...

  4. js解析url参数如http://www.taobao.com/index.php?key0=21&key1=你哈&(获取key0和key1的值)

    function parseQueryString(url) { var pos; var obj = {}; if ((pos = url.indexOf("?")) != -1 ...

  5. Linux下安装Python3.6和第三方库

    如果本机安装了python2,尽量不要管他,使用python3运行python脚本就好,因为可能有程序依赖目前的python2环境, 比如yum!!!!! 不要动现有的python2环境! 一.安装p ...

  6. LeetCode: Roman to Integer 解题报告

    Roman to IntegerGiven a roman numeral, convert it to an integer. Input is guaranteed to be within th ...

  7. LeetCode: Min Stack 解题报告

    Min Stack My Submissions Question Solution Design a stack that supports push, pop, top, and retrievi ...

  8. ajax的datatype选项的值

    jquery ajax方法 1."xml":返回 XML 文档,可用 jQuery 处理. 2."html"::返回纯文本 HTML 信息:包含的 script ...

  9. 一款纯css3实现的数字统计游戏

    今天给大家分享一款纯css3实现的数字统计游戏.这款游戏的规则的是将所有的数字相加等于72.这款游戏的数字按钮做得很美观,需要的时候可以借用下.一起看下效果图: 在线预览   源码下载 实现的代码. ...

  10. C语言 · Huffuman树

    基础练习 Huffuman树   时间限制:1.0s   内存限制:512.0MB        问题描述 Huffman树在编码中有着广泛的应用.在这里,我们只关心Huffman树的构造过程. 给出 ...