开发者

How to use an expression with a generic

Here's a class

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

And then in another class that takes a generic type argument I have something like:

repo = new Repository&开发者_开发问答lt;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. 

So, how to pass that expression?

UPD: Creating a type constraint class seems to be reasonable solution. But unfortunately doesn't work for me. TEntity in my case is an Entity Framework's EntityObject. Even If I try to create a constraint class and derived it from EntityObject or StructuralObject, compiler says: There is no implicit reference conversion


Declare "another class" with a type constraint in TEntity like:

class AnotherClass<TEntity> where TEntity : ISomethingWithId

where ISomethingWithId could be

interface ISomethingWithId {
   int Id {get;}
}

Then it should work...


Define an interface IEntity as

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

and then change the Repository class definition to

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

Ofcourse make sure TEntity implements IEntity interface and now your code would compile and work.


If TEntity is a generic type, but you know that any class passed in will have an Id property, you can add a type constraint on the generic class.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜