简体   繁体   中英

What is the use of generics in VB.NET?

I don't understand why write like this:

Class BlaBla(Of T as String)
End Class

Isn't it just the same as this:

Class BlaBla(ByVal str as String)
End Class

By the way, are you using Generics so often in your projects?

Isn't it just the same as this:

 Class BlaBla(ByVal str as String) End Class 

For one thing, you can't write that. So no, it's not the same. It's not even clear what you mean by that, ie what you expect this to do.

As for when to use generics: every time you want to reuse one particular class in conjunction with different types, without having to rewrite it every time.

The best example of this are collection classes, such as List(Of T) . If you don't know what this is: it's basically like an array, only with more operations. You can create arrays for different types: arrays of integers as well as arrays of strings. How would you get this same effect for your own Array implementation? The answer is: generics.

I think you are confusing declaration and usage.

The correct declaration would be just:

Public Class Foo(Of T)

What is T - well it can be pretty much anything you like. It is a generic type:

So you could use a string:

Dim bar as Foo(Of String)

You can use an integer

Dim bar as Foo(Of Integer)

You can use a class:

Dim bar as Foo(of MyClassThatICreated)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM