小编Chr*_*old的帖子

将通用列表转换为从列表派生的类

我创建了一个派生自List的类.但是,当我尝试将类转换为另一个List对象时,我收到运行时错误.我的代码类似于下面发布的代码:

public class CategoryObj
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
    public string Description { get; set; }
}

public class CategoryObjCollection:List<CategoryObj>
{

}

public void Test()
{
        CategoryObjCollection cat = new CategoryObjCollection();
        using (NWDataContext db = new NWDataContext())
        {
            var qry = (from c in db.Categories
                       select new CategoryObj
                       {
                           CategoryID = c.CategoryID,
                           CategoryName = c.CategoryName,
                           Description = c.Description
                       }).ToList();
            cat = (CategoryObjCollection)qry; //runtime error Unable to cast object of type …
Run Code Online (Sandbox Code Playgroud)

c#

7
推荐指数
2
解决办法
1287
查看次数

标签 统计

c# ×1