Tôi đang cố gắng để hiểu tại sao diễn viên này không làm việc:Tại sao ví dụ này không hoạt động?
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>();
}
}
}
này tạo ra một lỗi runtime:
InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[CastTest.Foo]' to type 'CastTest.FooList'.
bất cứ ai có thể giải thích tại sao điều này không làm việc, và cho dù tôi có thể nhận được xung quanh bằng cách nào đó?
Dòng nào tạo lỗi? – ChrisF
Điều gì là đúng để nói: Một FooList là một Danh sách, hoặc một Danh sách là một FooList? –
@AnthonyPegram Trước đây. – hvd