分享
 
 
 

[译]Visual Basic 2005在语言上的增强(四)泛型

王朝vb·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

BCL(Base Class Library,涕淌注)现在提供了System.Collections.Generic的命名空间,其中包括了不少定义了范型集合的类。之所以称之为“泛型”,是因为在定义的时候,你只是为其包含的对象指派了一个类型占位符,而不是将它定义为某个确定的类型。你只有在创建该集合的某个实例时,才会给它存储的对象指定一个特定的类型。

泛型极大地节省了我们的时间。如果你曾经创建过自定义集合,你就会体会到个中要添加多少的代码了。Visual Basic中的泛型可以让你只用一行的代码量,就创建出一个自定义集合的匹配物。你再也不必费神为你想存储的每种类型的对象创建各自独立的集合了。你仅需提供在你初始化一个泛型集合时你喜欢的某个类型。

想要了解泛型是如何工作的,最简单的方式是一起来看一个例子。假设你有一个简易的Customer类,它包含了两个公开的属性(为了简约,在下面被定义成了公共变量):

Public Class Customer

Public Name As String

Public CreditLimit As Decimal

Public Sub New(ByVal CustomerName As String, ByVal CustCreditLimit As Decimal)

Name = CustomerName

CreditLimit = CustCreditLimit

End Sub

End Class

你可以像下面那样声明一系列的Customers,其中使用到了泛型集合的List类:

Dim Customers As New System.Collections.Generic.List(Of Customer)

就仅仅这么一行代码,你就已经声明了一个仅能存储Customer类型的强类型列表,并且得到了关于其包含的Customer对象的完整的智能感知。你也同样可以创建一系列的Product或是Order对象,高效率地创建一套自定义集合,而无须为所有类型填写各自的代码。你可以像下面这样写:

Dim custA As New Customer("CustA", 1000)

Customers.Add(custA)

Dim custB As New Customer("CustB", 2000)

Customers.Add(custB)

For Each c As Customer In Customers

MessageBox.Show("Customer: " & c.Name & ", limit: " & c.CreditLimit)

Next

'编译错误:Product类型无法转换成Customer类型

Dim prodA As New Product("ProdA", CDec(29.95))

Customers.Add(prodA)

泛型集合的执行效率也毫不逊色,因为存储的对象是强类型的,而不是内在地被指定为Object类型。

在System.Collections.Generic命名空间下,还能找到其他的范型集合。譬如,Dictionary(Of K, V)集合允许你为关键字和值限定类型。LinkedList(Of T)及Stack(Of T)泛型集合的作用方式和普通的链表和堆栈无甚差别,只是你可以指定它们要存储的对象类型而已。

你可以使用新的泛型声明句法来创建你自己的泛型。我们来看看一个Comparer类,这个类可以用来比较两个不同类型的对象:

Public Class Comparer(Of itemType)

'...

End Class

你可以通过用逗号隔开的列表方式定义多重类型的占位符。你也可以定义一个约束条件来限制哪些类能在泛型初始化后提供给该泛型。

Public Class Comparer(Of itemType As IComparable)

'...

End Class

这个约束条件确保了Comparer(Of T)的实例只能通过那些实现了IComparable接口的类创建。多重约束条件也一样适用于类的声明。

作为一个示例,我们再来看一下这个扩充了的、实现了IComparable接口的Customer类:

Public Class Customer

Implements IComparable

Public Name As String

Public CreditLimit As Decimal

Public Sub New(ByVal CustomerName As String, ByVal CustCreditLimit As Decimal)

Name = CustomerName

CreditLimit = CustCreditLimit

End Sub

Public Function CompareTo(ByVal obj As Object) As Integer _

Implements IComparable.CompareTo

Dim c As Customer = CType(obj, Customer)

If CreditLimit > c.CreditLimit Then Return 1

If CreditLimit < c.CreditLimit Then Return -1

Return 0

End Function

End Class

类似地,Product类也可以被实现,不过CompareTo函数比较的是产品的价格而不是客户的存款限额:

Public Class Product

Implements IComparable

Public Name As String

Public Price As Decimal

Public Sub New(...)...

Public Function CompareTo(...)...

End Class

Comparer类提供了泛型比较操作:

Public Class Comparer(Of itemType As IComparable)

Public Function GetLargest(ByVal Item1 As itemType, _

ByVal Item2 As itemType) As itemType

Dim i As Integer = Item1.CompareTo(Item2)

If i > 0 Then Return Item1

If i < 0 Then Return Item2

Return Nothing

End Function

End Class

你现在可以用不同类型的对象来实例化Comparers(这里用复数没有别的意思,只是说你可以实例化多个Comparer实例,涕淌注)了:

Dim pc As New Comparer(Of Product)

Dim prod1 As New Product("LittleOne", 10)

Dim prod2 As New Product("BigOne", 100)

Dim lp As Product = pc.GetLargest(prod1, prod2)

MessageBox.Show("The more expensive product is: " & lp.Name)

Dim cc As New Comparer(Of Customer)

Dim cust1 As New Customer("SmallCo", 1000)

Dim cust2 As New Customer("LargeCo", 5000)

Dim lc As Customer = cc.GetLargest(cust1, cust2)

MessageBox.Show("The customer with a higher limit is: " & lc.Name)

若是没有了泛型,你就不得不为任何一种你想用来比较的对象类型分别定义一个比较类(比如说,ProductComparer和OrderComparer)。

在不少常见的场合,泛型都在很大程度上减轻了你的代码负担。想象一下吧,当你有着式样繁多的类,而它们仅仅在操作的对象类型上有所差别时,使用泛型会是多么利便的事。

@以下附上原文供大家参考@

Generics

The BCL now provides the System.Collections.Generic namespace, which contains several classes defining generic collections. They're called generic because at declaration you specify a type placeholder for the contained objects instead of a specific type. You give the stored objects a specific type only when you create an instance of the collection.

Generics are a huge time saver. If you've ever created custom collections, you know how much code can be involved. Generics in Visual Basic let you create the equivalent of a custom collection in one line of code. You no longer need to create separate custom collections for each type of object you want to store. You simply provide the desired type as you instantiate the generic collection.

The easiest way to see how generics work is with an example. Assume you have a simple Customer class with two public properties (shown as public variables for brevity):

Public Class Customer

Public Name As String

Public CreditLimit As Decimal

Public Sub New(ByVal CustomerName As String, ByVal CustCreditLimit As Decimal)

Name = CustomerName

CreditLimit = CustCreditLimit

End Sub

End Class

You can declare a list of Customers using the generic collection List class like so:

Dim Customers As New System.Collections.Generic.List(Of Customer)

With this single line of code, you've declared a strongly typed list that stores only Customer types and gives you full IntelliSense on the contained Customer objects. You could just as easily create a list of Product or Order objects, effectively creating a set of custom collections without writing all the custom collection code for each type. You can now write code like this:

Dim custA As New Customer("CustA", 1000)

Customers.Add(custA)

Dim custB As New Customer("CustB", 2000)

Customers.Add(custB)

For Each c As Customer In Customers

MessageBox.Show("Customer: " & c.Name & ", limit: " & c.CreditLimit)

Next

'compile error: Product cannot be converted to Customer

Dim prodA As New Product("ProdA", CDec(29.95))

Customers.Add(prodA)

You also get a performance advantage using generic collections because the stored objects are strongly typed and not kept internally as type Object.

There are other collection generics available in the System.Collections.Generic namespace. For example, the Dictionary(of K,V) collection allows you to specify types for the keys and values. The LinkedList(of T) and Stack(of T) generic collections behave like regular linked lists and stacks, except you're allowed to specify what kinds of objects they'll contain.

You can create your own generic types using the new generic type declaration syntax. Consider a Comparer class that lets you compare different kinds of objects:

Public Class Comparer(Of itemType)

'...

End Class

You can define multiple type placeholders in a comma-separated list. You can also define constraints restricting which classes can be provided to the generic when it's instantiated:

Public Class Comparer(Of itemType As IComparable)

'...

End Class

This constraint ensures that Comparer(of T) instances can only be created with classes implementing the IComparable interface. Multiple constraints can also be applied to the class declaration.

As an example, consider an expanded Customer class that implements IComparable:

Public Class Customer

Implements IComparable

Public Name As String

Public CreditLimit As Decimal

Public Sub New(ByVal CustomerName As String, ByVal CustCreditLimit As Decimal)

Name = CustomerName

CreditLimit = CustCreditLimit

End Sub

Public Function CompareTo(ByVal obj As Object) As Integer _

Implements IComparable.CompareTo

Dim c As Customer = CType(obj, Customer)

If CreditLimit > c.CreditLimit Then Return 1

If CreditLimit < c.CreditLimit Then Return -1

Return 0

End Function

End Class

A similar Product class is implemented, except that the CompareTo function compares the product prices instead of the customer's credit limits:

Public Class Product

Implements IComparable

Public Name As String

Public Price As Decimal

Public Sub New(...)...

Public Function CompareTo(...)...

End Class

Now the Comparer class provides the generic comparison operation:

Public Class Comparer(Of itemType As IComparable)

Public Function GetLargest(ByVal Item1 As itemType, _

ByVal Item2 As itemType) As itemType

Dim i As Integer = Item1.CompareTo(Item2)

If i > 0 Then Return Item1

If i < 0 Then Return Item2

Return Nothing

End Function

End Class

You can now instantiate Comparers with objects of different types:

Dim pc As New Comparer(Of Product)

Dim prod1 As New Product("LittleOne", 10)

Dim prod2 As New Product("BigOne", 100)

Dim lp As Product = pc.GetLargest(prod1, prod2)

MessageBox.Show("The more expensive product is: " & lp.Name)

Dim cc As New Comparer(Of Customer)

Dim cust1 As New Customer("SmallCo", 1000)

Dim cust2 As New Customer("LargeCo", 5000)

Dim lc As Customer = cc.GetLargest(cust1, cust2)

MessageBox.Show("The customer with a higher limit is: " & lc.Name)

Without generics, you'd have to define a comparison class for each type of object you want to compare (for example, ProductComparer and OrderComparer).

Generics can significantly reduce your coding efforts in many common scenarios. Consider using generics when you have multiple classes that vary only by the type of object on which they operate.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有