我必須在這裏錯過一些明顯的東西。我不明白爲什麼這個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