【发布时间】:2010-11-08 21:32:34
【问题描述】:
这个问题和这个问题有关:Given System.Type T, Deserialize List<T>
给定这个函数来检索所有元素的列表...
public static List<T> GetAllItems<T>()
{
XmlSerializer deSerializer = new XmlSerializer(typeof(List<T>));
TextReader tr = new StreamReader(GetPathBasedOnType(typeof(T)));
List<T> items = (List<T>)deSerializer.Deserialize(tr);
tr.Close();
}
...我想创建一个函数来仅检索具有所需 UID(唯一 ID)的项目中的一项:
public static System.Object GetItemByID(System.Type T, int UID)
{
IList mainList = GetAllItems<typeof(T)>();
System.Object item = null;
if (T == typeof(Article))
item = ((List<Article>)mainList).Find(
delegate(Article vr) { return vr.UID == UID; });
else if (T == typeof(User))
item = ((List<User>)mainList).Find(
delegate(User ur) { return ur.UID == UID; });
return item;
}
但是,这不起作用,因为 GetAllItems<typeof(T)>(); 调用的格式不正确。
问题 1a:考虑到所有将调用 GetItemByID() 的类都将 UID 作为其中的元素,我如何修复第二个函数以正确返回唯一元素?如果可能的话,我希望能够做到public static <T> GetItemByID<T>(int UID)。
问题 1b:同样的问题,但假设我不能修改 GetItemByID 的函数原型?
【问题讨论】:
标签: c# asp.net xml-serialization xml-deserialization generic-list