我一直在做C#OOP的速成课程,我很想知道下面的代码中"LIST"关键字代表什么:
var actors = new List<Actor>();
Run Code Online (Sandbox Code Playgroud)
List<T>是一个带有类型参数的类.这称为"泛型",允许您在类中不透明地操作对象,尤其适用于列表或队列等容器类.
容器只是存储东西,它实际上不需要知道它存储的是什么.我们可以在没有泛型的情况下实现它:
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*/ }
}
Run Code Online (Sandbox Code Playgroud)
但是,我们没有类型安全.我可以像这样滥用该集合中的地狱:
List list = new List( );
list.Add( 1 );
list.Add( "uh oh" );
list.Add( 2 );
int i = (int)list[1]; // boom goes the dynamite
Run Code Online (Sandbox Code Playgroud)
在C#中使用泛型允许我们以类型安全的方式使用这些类型的容器类.
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*/ }
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我们尝试添加一些不属于的东西,我们会得到编译时错误,这比我们的程序执行时发生的错误要好得多.
List<int> list = new List<int>( );
list.Add( 1 ); // fine
list.Add( "not this time" ); // doesn't compile, you know there is a problem
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.很抱歉,如果我在那里犯了任何语法错误,我的C#就生锈了;)