C# 泛型类中的Getter
我有一个泛型类,如下所示:C# 泛型类中的Getter,c#,C#,我有一个泛型类,如下所示: // K is key, T is type of content class myClass<K, T> { private List<T> items; private Dictionary<K, T> itemMap; } 当我将这个简单类用作T(使用id作为itemMap中的键)时: 通过otherParameter在items列表中查找此类实例的正确方法是什么?任何帮助都将不胜感激 在列表
// K is key, T is type of content
class myClass<K, T>
{
private List<T> items;
private Dictionary<K, T> itemMap;
}
当我将这个简单类用作T(使用id作为itemMap中的键)时:
通过otherParameter在items列表中查找此类实例的正确方法是什么?任何帮助都将不胜感激 在列表/字典中查找项目的方法就是:
myConcreteT search = ...
var item = items.Where(x => x.otherParameter == search.otherParameter)
.FirstOrDefault();
如果您想要“通用”版本,您可以将谓词与如下值一起传递给搜索函数:
T SearchByItem(T search, Func<T, T, bool> matches)
{
return items.Where(x => matches(x,search))
.FirstOrDefault();
}
T SearchByItem(T search,Func匹配)
{
返回项目。其中(x=>匹配(x,搜索))
.FirstOrDefault();
}
如果希望泛型类型T具有已知属性,则必须向泛型类定义添加约束。如果不可能,则调用方必须提供比较算法,如@Alexei Levenkov的答案所示
public interface IKnownProperties
{
int id {get;}
int otherParameter { get; }
}
// K is key, T is type of content
class myClass<K, T> where T:IKnownProperties
{
private List<T> items;
private Dictionary<K, T> itemMap;
}
class myConcreteT : IKnownProperties
{
int id {get;set;}
int otherParameter {get;set;}
}
公共接口IKnownProperties
{
int id{get;}
int其他参数{get;}
}
//K是关键,T是内容的类型
类myClass其中T:IKnownProperties
{
私人清单项目;
专用字典项目图;
}
类MyConcrete:IKnownProperties
{
int id{get;set;}
int其他参数{get;set;}
}
如果您试图在给定键的集合中查找项目,则应使用字典(或其他类似结构)而不是列表。您到底想在哪里查找实例?如果在myClass
中,则不可能,因为它不知道myConcreteT
有一个id
字段(如果您想从外部访问它,该字段必须是public
)。
T SearchByItem(T search, Func<T, T, bool> matches)
{
return items.Where(x => matches(x,search))
.FirstOrDefault();
}
public interface IKnownProperties
{
int id {get;}
int otherParameter { get; }
}
// K is key, T is type of content
class myClass<K, T> where T:IKnownProperties
{
private List<T> items;
private Dictionary<K, T> itemMap;
}
class myConcreteT : IKnownProperties
{
int id {get;set;}
int otherParameter {get;set;}
}