在使用LambdaExpression时,为多态类型指定泛型参数。
LambdaExpression在C#中常常用来创建动态查询表达式或委托。但在使用多态类型时,需要为其指定具体的泛型参数,否则编译器无法识别类型。下面是一个简单的代码示例:
//定义一个多态类型
public interface IRepository<T>
{
void Add(T item);
}
//定义两个不同的实体类
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Animal
{
public int Id { get; set; }
public string Species { get; set; }
}
//使用LambdaExpression创建一个动态查询表达式
public IQueryable<T> GetAll<T>(IRepository<T> repository, Expression<Func<T, bool>> predicate)
{
//为多态类型指定具体的泛型参数
return repository.Where(predicate);
}
//调用示例
var personRepository = new Repository<Person>();
var animalRepository = new Repository<Animal>();
var personQuery = GetAll<Person>(personRepository, p => p.Id == 1);
var animalQuery = GetAll<Animal>(animalRepository, a => a.Species == "cat");
这样,在使用LambdaExpression时,我们为多态类型指定了具体的泛型参数,使编译器能够正确地识别类型。