【发布时间】:2012-03-05 22:24:46
【问题描述】:
我试图理解为什么这个演员不起作用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CastTest {
class Foo {}
// I want to use this kind of like a typedef, to avoid writing List<Foo> everywhere.
class FooList : List<Foo> {}
class Program {
static void Main(string[] args) {
FooList list = (FooList) Program.GetFooList();
}
// Suppose this is some library method, and i don't have control over the return type
static List<Foo> GetFooList() {
return new List<Foo>();
}
}
}
这会产生一个运行时错误:
InvalidCastException:无法将“System.Collections.Generic.List`1[CastTest.Foo]”类型的对象转换为“CastTest.FooList”类型。
谁能解释为什么这不起作用,以及我是否能以某种方式解决这个问题?
【问题讨论】:
-
哪一行产生了错误?
-
哪种说法正确:FooList 是 List
,还是 List 是 FooList? -
如果你不喜欢额外的类型,使用隐式类型变量。像这样:
var list = Program.GetFooList(); -
到处写
List<Foo>有什么大问题?我曾经使用过一个强类型列表的代码库,这让我很痛苦。 -
@eouw0o83hf,在任何地方都写 List
并不是什么问题,但我只是想出了一个人为的例子来说明问题。我真的在尝试输入更长的类型名(如列表字典)