C#概念: "LIST"关键字代表什么?

4

我一直在进行C#面向对象编程的速成课程,想知道下面代码中的“LIST”关键字代表什么:

var actors = new List<Actor>();

1
我的 C# 可能有点生疏,但我认为那不是 C# 的语法...请记住,C# 是强类型的,所以 var foo = 不被允许(如果我没记错的话)。 - Sampson
5
@jonathan:它可以在C# 3.0及以上版本中使用。 http://msdn.microsoft.com/zh-cn/library/bb308966.aspx#csharp3.0overview_topic2 - Zen
3
@Jonathan:我相信这是C# 3.0的新功能。编译器根据初始化值的类型来推断变量的类型。http://msdn.microsoft.com/en-us/library/bb383973.aspx - outis
这真的必须是一个紧急课程,才会让你在C#中错过了集合。 - this. __curious_geek
@Zeno和@Outis:谢谢。我自2.0以来就没有碰过C#了。 - Sampson
4个回答

8
“List”是一个带有类型参数的类。这被称为“泛型”,它允许您在类中不透明地操作对象,特别适用于像列表或队列这样的容器类。
容器只是存储物品,它不需要真正知道它正在存储什么。我们可以像这样实现它而不使用泛型:
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*/ }
}

然而,我们没有类型安全性。我可以像这样滥用那个集合:
List list = new List( );
list.Add( 1 );
list.Add( "uh oh" );
list.Add( 2 );
int i = (int)list[1]; // boom goes the dynamite

在 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*/ } 
}

现在,如果我们尝试添加不属于的东西,我们会得到一个编译时错误,这比程序执行时发生错误要好得多。
List<int> list = new List<int>( );
list.Add( 1 );               // fine
list.Add( "not this time" ); // doesn't compile, you know there is a problem

希望有所帮助。如果我写错了语法,很抱歉,我的C#已经生疏了;)

5

这不是一个关键词,而是一个类标识符。


2

List<Actor>() 描述了一个 Actor 对象列表。通常,列表是一组按照某种方式排序并且可以通过索引访问的对象。


0

这不是一个通用的面向对象概念。它是.NET库中的一种类型。我建议选择一本好的C# & .NET书籍


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接