I have been doing a crash course of C# OOP and am curious to know what the "LIST" k开发者_开发问答eyword represents in the code below:
var actors = new List<Actor>();
List<T>
is a class with a type parameter. This is called "generics" and allows you to manipulate objects opaquely within the class, especially useful for container classes like a list or a queue.
A container just stores things, it doesn't really need to know what it is storing. We could implement it like this without generics:
class List
{
public List( ) { }
public void Add( object toAdd ) { /*add 'toAdd' to an object array*/ }
public void Remove( object toRemove ) { /*remove 'toRemove' from array*/ }
public object operator []( int index ) { /*index into storage array and return value*/ }
}
However, we don't have type safety. I could abuse the hell out of that collection like this:
List list = new List( );
list.Add( 1 );
list.Add( "uh oh" );
list.Add( 2 );
int i = (int)list[1]; // boom goes the dynamite
Using generics in C# allows us to use these types of container classes in a type safe manner.
class List<T>
{
// 'T' is our type. We don't need to know what 'T' is,
// we just need to know that it is a type.
public void Add( T toAdd ) { /*same as above*/ }
public void Remove( T toAdd ) { /*same as above*/ }
public T operator []( int index ) { /*same as above*/ }
}
Now if we try to add something that does not belong we get a compile time error, much preferable to an error that occurs when our program is executing.
List<int> list = new List<int>( );
list.Add( 1 ); // fine
list.Add( "not this time" ); // doesn't compile, you know there is a problem
Hope that helped. Sorry if I made any syntax errors in there, my C# is rusty ;)
It's not a keyword, it's a class identifier.
List<Actor>() is describing a list of Actor objects. Typically a list is a collection of objects that are ordered in some way and can be accessed by an index.
This is not a generic OO concept. It is a type in the .NET library. I would suggest to pick up a good C# & .NET book.
精彩评论