【发布时间】:2009-01-30 02:34:13
【问题描述】:
我必须在这里遗漏一些明显的东西。我不明白为什么这种 linq 查询结果的转换返回 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; }
}
【问题讨论】:
-
当您删除安全强制转换 ("as IList
") 时会发生什么?我认为您可以执行 .ToList() 并将其粘贴在您的 IList 变量中。 -
我也是这么想的,但是没用。