好吧,我想我有一些重复的代码可以使用泛型。如何实现使用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