php 泛型类,C#_深入解析C#中的泛型类与泛型接口,泛型类 泛型类封装不是特定 - phpStudy...

深入解析C#中的泛型类与泛型接口

泛型类

泛型类封装不是特定于具体数据类型的操作。泛型类最常用于集合,如链接列表、哈希表、堆栈、队列、树等。像从集合中添加和移除项这样的操作都以大体上相同的方式执行,与所存储数据的类型无关。

对于大多数需要集合类的方案,推荐的方法是使用 .NET Framework 类库中所提供的类。

一般情况下,创建泛型类的过程为:从一个现有的具体类开始,逐一将每个类型更改为类型参数,直至达到通用化和可用性的最佳平衡。创建您自己的泛型类时,需要特别注意以下事项:

将哪些类型通用化为类型参数。

通常,能够参数化的类型越多,代码就会变得越灵活,重用性就越好。但是,太多的通用化会使其他开发人员难以阅读或理解代码。

如果存在约束,应对类型参数应用什么约束。

一条有用的规则是,应用尽可能最多的约束,但仍使您能够处理必须处理的类型。例如,如果您知道您的泛型类仅用于引用类型,则应用类约束。这可以防止您的类被意外地用于值类型,并允许您对 T 使用 as 运算符以及检查空值。

是否将泛型行为分解为基类和子类。

由于泛型类可以作为基类使用,此处适用的设计注意事项与非泛型类相同。请参见本主题后面有关从泛型基类继承的规则。

是否实现一个或多个泛型接口。

例如,如果您设计一个类,该类将用于创建基于泛型的集合中的项,则可能必须实现一个接口,如 IComparable,其中 T 是您的类的类型。

类型参数和约束的规则对于泛型类行为有几方面的含义,特别是关于继承和成员可访问性。您应当先理解一些术语,然后再继续进行。对于泛型类 Node,客户端代码可通过指定类型参数来引用该类,以便创建封闭式构造类型 (Node)。或者可以让类型参数处于未指定状态(例如在指定泛型基类时)以创建开放式构造类型 (Node)。泛型类可以从具体的、封闭式构造或开放式构造基类继承:

class BaseNode { }

class BaseNodeGeneric { }

// concrete type

class NodeConcrete : BaseNode { }

//closed constructed type

class NodeClosed : BaseNodeGeneric { }

//open constructed type

class NodeOpen : BaseNodeGeneric { }

非泛型类(换句话说,即具体类)可以从封闭式构造基类继承,但无法从开放式构造类或类型参数继承,因为在运行时客户端代码无法提供实例化基类所需的类型参数。

//No error

class Node1 : BaseNodeGeneric { }

//Generates an error

//class Node2 : BaseNodeGeneric {}

//Generates an error

//class Node3 : T {}

从开放式构造类型继承的泛型类必须为任何未被继承类共享的基类类型参数提供类型变量,如以下代码所示:

class BaseNodeMultiple { }

//No error

class Node4 : BaseNodeMultiple { }

//No error

class Node5 : BaseNodeMultiple { }

//Generates an error

//class Node6 : BaseNodeMultiple {}

从开放式构造类型继承的泛型类必须指定约束,这些约束是基类型约束的超集或暗示基类型约束:

class NodeItem where T : System.IComparable, new() { }

class SpecialNodeItem : NodeItem where T : System.IComparable, new() { }

泛型类型可以使用多个类型参数和约束,如下所示:

class SuperKeyType

where U : System.IComparable

where V : new()

{ }

开放式构造类型和封闭式构造类型可以用作方法参数:

void Swap(List list1, List list2)

{

//code to swap items

}

void Swap(List list1, List list2)

{

//code to swap items

}

如果某个泛型类实现了接口,则可以将该类的所有实例强制转换为该接口。

泛型类是不变的。也就是说,如果输入参数指定 List,则当您尝试提供 List 时,将会发生编译时错误。

泛型接口为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 IComparable 而不使用 IComparable,这样可以避免值类型的装箱和取消装箱操作。.NET Framework 类库定义了若干泛型接口,以用于 System.Collections.Generic 命名空间中的集合类。

将接口指定为类型参数的约束时,只能使用实现此接口的类型。下面的代码示例显示从 SortedList 类派生的 GenericList 类。

SortedList 添加约束 where T : IComparable。这将使 SortedList 中的 BubbleSort 方法能够对列表元素使用泛型 CompareTo 方法。在此示例中,列表元素为简单类,即实现 Person 的 IComparable。

//Type parameter T in angle brackets.

public class GenericList : System.Collections.Generic.IEnumerable

{

protected Node head;

protected Node current = null;

// Nested class is also generic on T

protected class Node

{

public Node next;

private T data; //T as private member datatype

public Node(T t) //T used in non-generic constructor

{

next = null;

data = t;

}

public Node Next

{

get { return next; }

set { next = value; }

}

public T Data //T as return type of property

{

get { return data; }

set { data = value; }

}

}

public GenericList() //constructor

{

head = null;

}

public void AddHead(T t) //T as method parameter type

{

Node n = new Node(t);

n.Next = head;

head = n;

}

// Implementation of the iterator

public System.Collections.Generic.IEnumerator GetEnumerator()

{

Node current = head;

while (current != null)

{

yield return current.Data;

current = current.Next;

}

}

// IEnumerable inherits from IEnumerable, therefore this class

// must implement both the generic and non-generic versions of

// GetEnumerator. In most cases, the non-generic method can

// simply call the generic method.

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()

{

return GetEnumerator();

}

}

public class SortedList : GenericList where T : System.IComparable

{

// A simple, unoptimized sort algorithm that

// orders list elements from lowest to highest:

public void BubbleSort()

{

if (null == head || null == head.Next)

{

return;

}

bool swapped;

do

{

Node previous = null;

Node current = head;

swapped = false;

while (current.next != null)

{

// Because we need to call this method, the SortedList

// class is constrained on IEnumerable

if (current.Data.CompareTo(current.next.Data) > 0)

{

Node tmp = current.next;

current.next = current.next.next;

tmp.next = current;

if (previous == null)

{

head = tmp;

}

else

{

previous.next = tmp;

}

previous = tmp;

swapped = true;

}

else

{

previous = current;

current = current.next;

}

}

} while (swapped);

}

}

// A simple class that implements IComparable using itself as the

// type argument. This is a common design pattern in objects that

// are stored in generic lists.

public class Person : System.IComparable

{

string name;

int age;

public Person(string s, int i)

{

name = s;

age = i;

}

// This will cause list elements to be sorted on age values.

public int CompareTo(Person p)

{

return age - p.age;

}

public override string ToString()

{

return name + ":" + age;

}

// Must implement Equals.

public bool Equals(Person p)

{

return (this.age == p.age);

}

}

class Program

{

static void Main()

{

//Declare and instantiate a new generic SortedList class.

//Person is the type argument.

SortedList list = new SortedList();

//Create name and age values to initialize Person objects.

string[] names = new string[]

{

"Franscoise",

"Bill",

"Li",

"Sandra",

"Gunnar",

"Alok",

"Hiroyuki",

"Maria",

"Alessandro",

"Raul"

};

int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };

//Populate the list.

for (int x = 0; x < 10; x++)

{

list.AddHead(new Person(names[x], ages[x]));

}

//Print out unsorted list.

foreach (Person p in list)

{

System.Console.WriteLine(p.ToString());

}

System.Console.WriteLine("Done with unsorted list");

//Sort the list.

list.BubbleSort();

//Print out sorted list.

foreach (Person p in list)

{

System.Console.WriteLine(p.ToString());

}

System.Console.WriteLine("Done with sorted list");

}

}

可将多重接口指定为单个类型上的约束,如下所示:

class Stack where T : System.IComparable, IEnumerable

{

}

一个接口可定义多个类型参数,如下所示:

interface IDictionary

{

}

适用于类的继承规则同样适用于接口:

interface IMonth { }

interface IJanuary : IMonth { } //No error

interface IFebruary : IMonth { } //No error

interface IMarch : IMonth { } //No error

//interface IApril : IMonth {} //Error

如果泛型接口为逆变的,即仅使用其类型参数作为返回值,则此泛型接口可以从非泛型接口继承。在 .NET Framework 类库中,IEnumerable 从 IEnumerable 继承,因为 IEnumerable 只在 GetEnumerator 的返回值和 Current 属性 getter 中使用 T。

具体类可以实现已关闭的构造接口,如下所示:

interface IBaseInterface { }

class SampleClass : IBaseInterface { }

只要类参数列表提供了接口必需的所有参数,泛型类便可以实现泛型接口或已关闭的构造接口,如下所示:

interface IBaseInterface1 { }

interface IBaseInterface2 { }

class SampleClass1 : IBaseInterface1 { } //No error

class SampleClass2 : IBaseInterface2 { } //No error

相关阅读:

C++、python和go语言实现的简单客户端服务器代码示例

js 剪切板的用法(clipboardData.setData)与js match函数介绍

Linux桌面分辨率在哪如何修改桌面分辨率

MySQL全局共享内存介绍

Android中实现多行、水平滚动的分页的Gridview实例源码

js生成缩略图后上传并利用canvas重绘

CSS中float和clear各是什么意思有哪些区别

JavaScript+html5 canvas制作色彩斑斓的正方形效果

win10升级后软件会没吗?升级Win10:哪些东西会丢失

Win10正式版升级到89%电脑自动重启之后硬盘数据全部丢失该怎么办?

mod_php、FastCGI、PHP-FPM等PHP运行方式对比

在CentOS系统中检测Java安装及运行jar应用的方法

Java编程中正则表达式的用法总结

sqlserver 因为选定的用户拥有对象,所以无法除去该用户的解决方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值