在下面的方法中,我嘗試從一種類型的對象中選擇特定的ID。以上所有的工作,但最後一部分,我把查詢中的對象交給特定對象類型(T)的列表會產生問題,下面的方法也不接受我的輸入。我可以想象,在運行時這應該都可以正常工作,但visual-studio不接受它。如何以正確的方式移交我的對象類型?
private static Guid[] SelectiveQuery<T>(Guid[] ga, T input, string a)
{
List<T> li = new List<T>();
foreach (Guid g in ga)
{
var query = from produkt in Entity.ProduktCollection.produktCollection
let p = produkt as Entity.Produkt
from version in p.version
let v = version as Entity.Version
from customer in v.customerCollection
let c = customer as Entity.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Fehler
select new {p, v, c, f};
switch (a)
{
case "produkt":
query = query.Where(x => x.p.id == g); break;
case "version":
query = query.Where(x => x.v.id == g); break;
case "customer":
query = query.Where(x => x.c.id == g); break;
case "fehler":
query = query.Where(x => x.f.id == g); break;
case "kategorie":
query = query.Where(x => x.f.kategorie.id == g); break;
}
query = query.Where(x => x.GetType() == typeof(T));
li.AddRange(query); //contains error ("System.Collections.Generic.IEnumerable<AnonymousType#1>" can't be converted to "System.Collections.Generic.IEnumerable<T>"
}
// Reduce() removes duplicates in li and returns the list
li = Reduce(li, i => i.id); //contains error (T doesn't contain a definition for id)
// Guids() makes a list of all IDs inside li and returns this List<Guid>
return Guids(li, i => i.id); //contains error (T doesn't contain a definition for id)
}
對於「T不包含id的定義」,我認爲你應該使用「where T:」和一個接口來定義id必須可用。 –
@Thomas W.你能舉個例子嗎?我不是很確定,我知道你的意思 –