如何使用带有泛型的表达式

时间:2011-07-15 17:27:54

标签: generics c#-4.0 lambda expression

这是一个班级

public class Repository<T>
{
  T GetSingle(Expression<Func<T, bool>> condition);
}

然后在另一个采用泛型类型参数的类中,我有类似的东西:

repo = new Repository<TEntity>();
repo.GetSingle(x=> x.Id == 1); 
// That won't compile because TEntity is a generic type. 
//Compiler doesn't know if TEntity has Id or not. 

那么,如何传递那个表达式?

UPD:创建类型约束类似乎是合理的解决方案。但不幸的是对我不起作用。在我的案例中,TEntity是一个Entity Framework的EntityObject。即使我尝试创建一个约束类并从EntityObject或StructuralObject派生它,编译器说:没有隐式引用转换

3 个答案:

答案 0 :(得分:3)

TEntity中声明具有类型约束的“另一个类”,如:

class AnotherClass<TEntity> where TEntity : ISomethingWithId

其中ISomethingWithId可能是

interface ISomethingWithId {
   int Id {get;}
}

然后它应该工作......

答案 1 :(得分:2)

将界面IEntity定义为

public interface IEntity 
{
    long Id{get; set;}
}

然后将Repository类定义更改为

public class Repository<T> : where T:IEntity
{
     T GetSingle(Expression<Func<T, bool>> condition); 
}

当然要确保 TEntity 实现 IEntity 界面,现在您的代码可以编译并运行。

答案 2 :(得分:2)

如果TEntity是泛型类型,但您知道传入的任何类将具有Id属性,则可以在泛型类上添加类型约束。

public interface IEntity
{
    int Id;
}

public class Entity : IEntity
{
    public int Id;
}

public class Test<TEntity> where TEntity : Entity // generic type constraint
{
    private void test()
    {
        var repo = new Repository<TEntity>();
        repo.GetSingle(x => x.Id == 1);
    }
}