泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用在集合和在集合上运行的方法中。.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。

 
// type parameter T in angle brackets
public class GenericList<T>
{
// The nested class is also generic on T
private class Node
{
// T used in non-generic constructor
public Node(T t)
{
next = null;
data = t;
} private Node next;
public Node Next
{
get { return next; }
set { next = value; }
} // T as private member data type
private T data; // T as return type of property
public T Data
{
get { return data; }
set { data = value; }
}
} private Node head; // constructor
public GenericList()
{
head = null;
} // T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
} public IEnumerator<T> GetEnumerator()
{
Node current = head; while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}

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

 
class TestGenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>(); for (int x = 0; x < 10; x++)
{
list.AddHead(x);
} foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("\nDone");
}
}

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

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

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

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


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Test with a non-empty list of integers.
            GenericList<int> gll = new GenericList<int>();
            gll.AddNode(5);
            gll.AddNode(4);
            gll.AddNode(3);
            int intVal = gll.GetLast();
            // The following line displays 5.
            System.Console.WriteLine(intVal);             // Test with an empty list of integers.
            GenericList<int> gll2 = new GenericList<int>();
            intVal = gll2.GetLast();
            // The following line displays 0.
            System.Console.WriteLine(intVal);             // Test with a non-empty list of strings.
            GenericList<string> gll3 = new GenericList<string>();
            gll3.AddNode("five");
            gll3.AddNode("four");
            string sVal = gll3.GetLast();
            // The following line displays five.
            System.Console.WriteLine(sVal);             // Test with an empty list of strings.
            GenericList<string> gll4 = new GenericList<string>();
            sVal = gll4.GetLast();
            // The following line displays a blank line.
            System.Console.WriteLine(sVal);
        }
    }     // T is the type of data stored in a particular instance of GenericList.
    public class GenericList<T>
    {
        private class Node
        {
            // Each node has a reference to the next node in the list.
            public Node Next;
            // Each node holds a value of type T.
            public T Data;
        }         // The list is initially empty.
        private Node head = null;         // Add a node at the beginning of the list with t as its data value.
        public void AddNode(T t)
        {
            Node newNode = new Node();
            newNode.Next = head;
            newNode.Data = t;
            head = newNode;
        }         // The following method returns the data value stored in the last node in
        // the list. If the list is empty, the default value for type T is
        // returned.
        public T GetLast()
        {
            // The value of temp is returned as the value of the method. 
            // The following declaration initializes temp to the appropriate 
            // default value for type T. The default value is returned if the 
            // list is empty.
            T temp = default(T);             Node current = head;
            while (current != null)
            {
                temp = current.Data;
                current = current.Next;
            }
            return temp;
        }
    }

}

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. cancas绘制折线图

    知识点回顾: 知识点1: measureText() 方法返回包含一个对象,该对象包含以像素计的指定字体宽度. 提示:如果您需要在文本向画布输出之前,就了解文本的宽度,那么请使用该方法. JavaSc ...

  2. C++访问mysql数据库

    C++连接mysql数据库,并取数据进行显示本例中,在mysql中已经存在了一个数据库test,并在test数据库中创建了一张表stu做测试,表中包含3个字段 需要把mysql目录下的libmysql ...

  3. C++面向对象程序设计的一些知识点(5)

    摘要:运算符能给程序员提供一种书写数学公式的感觉,本质上运算符也是一种函数,因此有类内部运算符和全局运算符之分,通过重载,运算符的“动作”更加有针对性,编写代码更像写英文文章. 1.C++标准允许将运 ...

  4. u-boot mkconfig文件分析

    #!/bin/sh -e #遇到非0返回 就退出脚本 # Script to create header files and links to configure # U-Boot for a spe ...

  5. python+xpath+requests爬取维基百科历史上的今天

    import requests import urllib.parse import datetime from lxml import etree fhout = open("result ...

  6. RTX——第11章 临界段,任务锁和中断锁

    以下内容转载自安富莱电子: http://forum.armfly.com/forum.php 临界段代码的临界段也称为临界区,一旦这部分代码开始执行,则不允许任何中断打断.为确保临界段代码的执行不被 ...

  7. MongoDB学习之(二)java连接

    上一章完了下mongodb的安装和IDE工具,现在开始使用java进行连接. 第一步:使用jar包, 这里需要三个包,具体为啥我也不清楚,反正因为报错,我就按照官方文档一个个的都下载了. 链接:htt ...

  8. 编程精粹--编写高质量C语言代码(1):假想编译程序

    编译程序只能查找出程序的语法错误,而对于"数组越界訪问","对空指针解引用"等错误.编译程序是束手无策的.同一时候我们知道測试人员所使用的黑箱測试方法所能做的不 ...

  9. list集合绑定在datagridview上时如何实现排序

    List<Person> lst = new List<Person>(); lst.Add(new Person("A", "1")) ...

  10. 简单5步,释放Mac磁盘空间

    收藏一下,以备后用 http://ourmacs.com/mactech/340