好吧,我想我有一些重複的代碼可以使用泛型。如何實現使用Linq和XML的泛型方法
我有兩個不同的Xml文件,我打開,查詢並返回爲綁定到GridViews的集合。這些集合是使用xml中的數據填充的自定義類的列表。每個gridview都有其相應的自定義類。目前我有兩個,並說這些類的名稱是XmlDataSource1和XmlDataSource2。
下面是當前使用XmlDataSource1作爲示例的工作示例。請注意,XmlDataSource1對象的構造函數從查詢中獲取XElements並填充自身。沒有瘋狂。
GridView gv = new GridView();
gv.DataSource = GetXmlDataSource1(pathToXmlFile);
gv.DataBind();
public List<XmlDataSource1> GetXmlDataSource1(string pathToXmlFile)
{
XDocument xml = XDocument.Load(pathToXmlFile);
IEnumerable<XmlDataSource1> query = from s in xml.Descendants("NodeForXml1")
select new XmlDataSource1(s);
// Where clauses based on user inputs (deferred execution)
query = query.Where(x => x.ID = SomeUserInputId);
// More of these where clauses if they have inputs for them...
// Convert to a List and return
return query.ToList();
}
現在,要實現GetXmlDataSource2()方法,它就像98%一樣。當然,主要不同之處在於,linq查詢的select部分創建XmlDataSource2對象的新實例,「NodeForXml2」後代目標節點,以及某些應用/不適用的子句。
如何讓這些GetXmlDataSource#方法具有通用性?理想情況下,我想調用它,如下所述,這是我所嘗試的,但我不能讓linq查詢的選擇部分調用正確的數據對象的構造函數。
GridView gv1 = new GridView();
GridView gv2 = new GridView();
gv1.DataSource = GetXmlDataSource<XmlDataSource1>(pathToXmlFile);
gv2.DataSource = GetXmlDataSource<XmlDataSource2>(pathToXmlFile);
gv1.DataBind();
gv2.DataBind();
public List<T> GetXmlDataSource<T>(string pathToXmlFile)
{
// The type of T in case I need it
Type typeOfT = typeof(T);
XDocument xml = XDocument.Load(pathToXmlFile);
// How to make new XmlDataSource1 and 2 objects?? This statement doesn't work.
IEnumerable<T> query = from s in xml.Descendants("NodeForXml1")
select new T(s);
// How to return the IEnumerable query to a List of the T's?
return query.ToList();
}
我有多遠?我關門了嗎?
嗯,你是什麼意思「我不能得到選擇部分的linq查詢來調用正確的數據對象的構造函數」 ...?你有錯誤嗎? –
@JeffBridgman是的,我得到了一個異常,因爲它沒有調用相應的構造函數來傳遞T.我從AirL實現了下面提到的方法,並且這些構造函數被激發。不過,我現在正在閱讀有關可能的性能問題,看看這是否是最好的方法。 – bdizzle