2012-05-10 106 views
-1

您好,我有一個關於正確使用遺傳的問題。對象的通用接口創建取決於某種類型

請看看我的代碼,我需要一個建議,是否有可能以其他方式創建基本搜索。我想從Conc2Search和Conc1Search類中刪除ISearcher的限制。

class Program 
{ 
    static void Main(string[] args) 
    { 
     var res1 = SearchCreator.GetSearch(1).Search(); 
     Console.WriteLine("GenetalSearch count:{0}", res1.Count()); 

     var res2 = SearchCreator.GetSearch(2).Search(); 
     Console.WriteLine("Conc1Search count:{0}", res2.Count()); 

     var res3 = SearchCreator.GetSearch(3).Search(); 
     Console.WriteLine("Conc2Search count:{0}", res3.Count()); 
    } 

    public class SearchCreator 
    {   
     public static ISearcher<Base> GetSearch(int type) 
     { 
      switch (type) 
      { 
       case 1: return new GenetalSearch(); 
       case 2: return new Conc1Search(); 
       case 3: return new Conc2Search(); 
      } 
      return null; 
     } 
    } 
} 


public class Base 
{ 

} 

public class Conc1 : Base 
{ 

} 

public class Conc2 : Base 
{ 

} 

public interface ISearcher<out T> where T : Base 
{ 
    IEnumerable<T> Search(); 
} 


public class GenetalSearch : ISearcher<Base> 
{ 
    public IEnumerable<Base> Search() 
    { 
     var list = new List<Base> {new Base(), new Base(), new Base()}; 
     return list; 
    } 
} 

public class Conc1Search : ISearcher<Conc1>, ISearcher<Base> 
{ 
    public IEnumerable<Conc1> Search() 
    { 
     var list = new List<Conc1>() { new Conc1(), new Conc1(), new Conc1(), new Conc1()}; 
     return list; 
    } 

    IEnumerable<Base> ISearcher<Base>.Search() 
    { 
     return Search(); 
    } 
} 

public class Conc2Search : ISearcher<Conc2>, ISearcher<Base> 
{ 
    public IEnumerable<Conc2> Search() 
    { 
     var list = new List<Conc2>() { new Conc2(), new Conc2(), new Conc2(), new Conc2(), new Conc2() }; 
     return list; 
    } 

    IEnumerable<Base> ISearcher<Base>.Search() 
    { 
     return Search(); 
    } 
} 

回答

2

什麼:

public interface ISearcher<T> 
{ 
    IEnumerable<T> Search(); 
} 

public class GeneralSearch<T> : ISearcher<T> where T : new() 
{ 
    public static IEnumerable<T> Search() 
    { 
     var list = new List<T> { new T(), new T(), new T() }; 
     return list; 
    } 
} 

再例如:

IEnumerable<myClass> test = GeneralSearch<myClass>.Search(); 
+1

看起來不錯謝謝 –

相關問題