通用列表问题
我有这样的对象。
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 从一种类型转换为另一种类型。
I have my objects like this.
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
{
}
and a test class
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>;
}
}
but I am getting null result returned from GetAllActiveData method.
Is there anyway I convert IList from one type to another.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有一个问题,因为您实际上并没有创建派生类的任何实例。您需要实际创建
CarFuelType
实例,而不是BaseTable
。完成此操作后,您将不需要任何转换。您可以通过这种方式做到这一点 - 至少对于 LINQ to Objects:我怀疑这是否适用于 LINQ to SQL 或实体框架...您可能必须在 LINQ to SQL 查询中创建 BaseTable 实例,然后在内存中转换它们,例如,
这可能会失去“实体性”,但是 - 您可能会在使用这些对象进行更新等时遇到问题。
You've got a problem here, because you're not actually creating any instances of the derived class. You need to actually create instances of
CarFuelType
rather thanBaseTable
. Once you've done that, you won't need any casting. You can do that in this way - at least for LINQ to Objects:I doubt this will work for LINQ to SQL or the Entity Framework though... you'd probably have to create instances of BaseTable in the LINQ to SQL query, then convert them in memory, e.g.
That may lose the "entity-ness" however - you may have problems using those objects for updates etc.