对象的通用接口创建取决于某种类型

时间:2012-05-10 16:36:46

标签: c# oop

您好我有一个关于以正确方式使用遗传的问题。

请查看我的代码,我需要建议,是否可以通过其他方式创建基本搜索。我想从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();
     }
}

1 个答案:

答案 0 :(得分: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();