【问题标题】:How to use an expression with a generic如何将表达式与泛型一起使用
【发布时间】:2011-07-15 17:27:53
【问题描述】:

这是一堂课

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 是一个实体框架的 EntityObject。即使我尝试创建一个约束类并从 EntityObject 或 StructuralObject 派生它,编译器也会说:没有隐式引用转换

【问题讨论】:

  • 可以添加TEntity的代码定义吗?

标签: generics c#-4.0 lambda expression


【解决方案1】:

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

class AnotherClass<TEntity> where TEntity : ISomethingWithId

ISomethingWithId 可能在哪里

interface ISomethingWithId {
   int Id {get;}
}

那么它应该可以工作......

【讨论】:

  • 现在,如果 TEntity 是从 System.Data.Objects.DataClasses.EntityObject 派生的,我需要一些可以工作的东西
【解决方案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 接口,这样您的代码就可以编译并工作了。

【讨论】:

    【解决方案3】:

    如果 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2022-01-20
      • 2011-02-09
      • 2019-03-21
      • 1970-01-01
      相关资源
      最近更新 更多