gpt4 book ai didi

c# - 根据 ID 从 List 中获取一个元素

转载 作者:行者123 更新时间:2023-11-30 16:32:20 26 4
gpt4 key购买 nike

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

最佳答案

1a.确保所有 T 实现定义属性 UID 的接口(interface) IUniqueIdentity,然后约束通用方法仅接受 IUniqueIdentity 类型。所以:

public static T GetItemById<T>(int UID) where T:IUniqueIdentity
{
IList<T> mainList = GetAllItems<T>();

//assuming there is 1 or 0 occurrences, otherwise FirstOrDefault
return mainList.SingleOrDefault(item=>item.UID==UID);

}

public interface IUniqueIdentity
{
int UID{get;}
}

关于c# - 根据 ID 从 List<T> 中获取一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4128270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com