这个问题与这个问题有关: 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 的函数原型?