2011-01-20 52 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方法中使用接口成員。