我必须在这里错过一些明显的东西。我不明白为什么这个linq查询结果的转换返回null,而不是我请求的类型化列表。Linq - 将IQueryable投射到IList返回null - 为什么?
IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
运行此操作的完整代码如下所示。这是我需要弥补的知识缺口。我尝试了各种各样的演员阵容,以使其发挥作用。我没有得到例外,只是一个空。值得注意的是,LINQ查询是选择它的成果转化为我定制的“MyDataClass”它实现IMyDataInterface
class Program
{
static void Main(string[] args)
{
IMyFunctionalInterface myObject = new MyClass();
//myObject.Get() returns null for some reason...
IList<IMyDataInterface> list = myObject.Get();
Debug.Assert(list != null, "Cast List is null");
}
}
public interface IMyFunctionalInterface
{
IList<IMyDataInterface> Get();
}
public class MyClass : IMyFunctionalInterface
{
public IList<IMyDataInterface> Get()
{
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
var query = from n in names
where n.Contains("a")
select new MyDataClass
{
Name = n.ToString()
};
//There IS data in the query result
Debug.Assert(query != null, "result is null");
//but the cast here makes it return null
IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
return list;
}
}
public interface IMyDataInterface
{
string Name { get; set; }
}
public class MyDataClass : IMyDataInterface
{
public string Name { get; set; }
}
会发生什么( “为IList的”)?我认为你可以执行.ToList()并将它粘贴在你的IList 变量中。 –
2009-01-30 03:13:41
我也这么认为,但没有奏效。 – jlembke 2009-02-01 22:39:19