2011-01-20 53 views
2

请参阅下面的代码。我想对一些属性进行一些检查(例如,在IsActive上)。你能告诉我在我的情况下如何在GetList()中实现这个?对实现接口的对象进行LINQ查询

感谢,

public interface ILookup 
    { 
     int Id { get; set; } 
     string FR { get; set; } 
     string NL { get; set; } 
     string EN { get; set; } 
     bool IsActive { get; set; } 
    } 

    public class LookupA : ILookup 
    { 

    } 
    public class LookupB : ILookup 
    { 

    } 

    public interface ILookupRepository<T> 
    { 
     IList<T> GetList(); 
    } 


    public class LookupRepository<T> : ILookupRepository<T> 
    { 
     public IList<T> GetList() 
     { 
      List<T> list = Session.Query<T>().ToList<T>(); 
      return list; 
     }  
    } 

回答

3

如果你知道T将会类型的ILookup你需要把一个约束它就像这样:

public interface ILookup 
{ 
    int Id { get; set; } 
    string FR { get; set; } 
    string NL { get; set; } 
    string EN { get; set; } 
    bool IsActive { get; set; } 
} 

public class LookupA : ILookup 
{ 

} 
public class LookupB : ILookup 
{ 

} 

public interface ILookupRepository<T> 
{ 
    IList<T> GetList(); 
} 


public class LookupRepository<T> : ILookupRepository<T> where T : ILookup 
{ 
    public IList<T> GetList() 
    { 
     List<T> list = Session.Query<T>().Where(y => y.IsActive).ToList<T>(); 
     return list; 
    }  
} 
+1

Darn,秒杀我; p另外:在我的代码中,我还在`ILookupRepository `上有'where T:ILookup`,因为它听起来像它总是和`ILookup`一起使用 - 也许一个用于OP思考...... – 2011-01-20 06:47:04

+0

我对'ILookupRepository`也有约束但是删除了它。原因是我没有看到将ILookupRepository仅限制为一种类型的理由,即使'interface'的名称是这样的。我不会不必要地限制自己。 – 2011-01-20 06:55:46

0

你应该能够利用Generic Constraints来帮助你出。

首先,改变你的接口定义:

public interface ILookupRepository<T> where T : ILookup 
//         ^^^^^^^^^^^^^^^^^ 

其次,改变你的类定义相匹配的约束:

public class LookupRepository<T> : ILookupRepository<T> where T : ILookup 
//              ^^^^^^^^^^^^^^^^^ 

约束将要求泛型类型参数来实现ILookup。这将允许您在GetList方法中使用接口成员。