通用列表问题

时间:2009-11-15 09:02:03

标签: c# generics ilist

我有这样的对象。

public class BaseTable
{
    public int ID               { get; set; }
    public int ParentID         { get; set; }
    public string Description   { get; set; }
    public bool IsActive        { get; set; }    

}

public class CarFuelType : BaseTable
{

}

和测试类

public class Test
{
    public IList<CarFuelType> GetAllActiveFuelTypes()
    {
        var result = GetAllActiveData<CarFuelType>(LookUpTableConstants.CarFuelType);

        return result.Cast<CarFuelType>().ToList(); 
    }


    private IList<T> GetAllActiveData<T>(int filter)
    {
        var result = from c in _lookUpTableValuesRepository.GetAllRowsWhere(l => l.ParentID == filter && l.IsActive==true)
                     select new BaseTable{ ID = c.ID, Description = c.Description, ParentID = c.ParentID };
        return result.ToList() as IList<T>;
    }

}

但是我从GetAllActiveData方法返回null结果。 无论如何我将IList从一种类型转换为另一种类型。

1 个答案:

答案 0 :(得分:6)

这里有一个问题,因为你实际上并没有创建派生类的任何实例。您需要实际创建CarFuelType而不是BaseTable的实例。一旦你完成了,你将不需要任何铸造。你可以这样做 - 至少对于LINQ to Objects:

private IList<T> GetAllActiveData<T>(int filter) where T : BaseTable, new()
{
    var result = from c in _lookUpTableValuesRepository
                               .GetAllRowsWhere(l => l.ParentID == filter 
                                                && l.IsActive==true)
                 select new T() { ID = c.ID, 
                                  Description = c.Description,
                                  ParentID = c.ParentID };
    return result.ToList();
}

我怀疑这对于LINQ to SQL或实体框架是否有用......你可能不得不在LINQ to SQL查询中创建BaseTable实例,然后在内存中转换它们,例如。

    var baseQuery = from c in _lookUpTableValuesRepository
                               .GetAllRowsWhere(l => l.ParentID == filter 
                                                && l.IsActive==true)
                 select new BaseTable { ID = c.ID, 
                                        Description = c.Description,
                                        ParentID = c.ParentID };

    var converted = baseQuery.AsEnumerable()
                             .Select(b => new T() { ID = b.ID, 
                                                    Description = b.Description,
                                                    ParentID = b.ParentID };

然而,这可能会失去“实体性” - 您可能无法使用这些对象进行更新等。

相关问题