对象的通用接口创建取决于某种类型
本文关键字:取决于 种类 类型 创建 接口 对象 | 更新日期: 2023-09-27 18:33:43
你好,我有一个关于正确使用遗传的问题。
请查看我的代码,我需要建议,是否可以以其他方式创建基本搜索。我想从Conc2Search和Conc1Search类中删除ISearcher impementation。
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();
}
}
怎么样:
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();