Getter在泛型类中

时间:2015-09-02 14:45:36

标签: c#

我有一个泛型类,如下所示:

// K is key, T is type of content
class myClass<K, T>
{
    private List<T> items;
    private Dictionary<K, T> itemMap;
}        

按键吸气:

public T get(K index)
{
    if (this.itemMap.ContainsKey(index))
    {
        return this.itemMap[index];
    }
    else
    {
       // no key found
        return default(T); 
    }
}

当我将这个简单的类用作T(在itemMap中使用id作为键)时:

class myConcreteT 
{
    int id;
    int otherParameter;
}

通过 otherParameter 在项目列表中查找此类实例的正确方法是什么?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

在list / dictionary中查找项目的方法就是Where:

  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();
  }

答案 1 :(得分:2)

如果希望泛型类型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;}
}
相关问题