[英]How to assign different generic classes to same variable
我知道这个问题可能已经被问过很多次了,我的书名可能需要一些帮助,因此在将我指向重复的对象后可以随时结束这个问题……只是不确定目前如何正确地寻找答案。
我遇到一种情况,其中变量可能需要保存ISolrOperations<Class1>
实例,或者它可能需要保存ISolrOperations<Class2>
的实例。 问题在于该接口没有基础版本,因此没有类可以定义为变量(对象除外,该对象显然不了解ISolrOperations<T>
的方法)可以容纳这两个类。
因此,我知道的唯一解决方案是:a)执行if / else语句,在其中我用ISolrOperations<Class1>
在一个块中完成我需要做的一切,而在ISolrOperations<Class2>
中在另一块中执行我需要做的一切,即使每个块基本上包含重复的代码。 或者b)我可以使变量动态化,而只是失去一些对我的代码的编译时验证。
我试图考虑是否可以通过某种方式创建具有非泛型基础的泛型包装器类。 也许底座必须将其视为对象,但要使用反射...但是它们就像螺丝钉一样。 如果我必须解决该麻烦,也可以使用dynamic关键字。
有没有更“合适”的设计模式来处理这种情况? 还是在动态还是写很多代码之间做出选择,以使自己觉得在动态是最实际的解决方案时我做对了?
编辑:其实我不确定动态是否可以解决此问题:/
编辑2:不...其他代码使用带变量的lambdas要求强制转换它,我显然不知道在编译时强制转换为什么,这样就行不通了。
尽管我不确定,但是这种方法可能会有所帮助。 此方法使用适配器模式 。
public interface ISolrOperations<T>
{
SqlQuery<T> Execute();
}
public interface ISolrOperationsAdapter
{
IEnumerable<Base> Execute();
}
//Idealy you have interfaces
public class Base { }
public class Class1 : Base { }
public class Class2 : Base { }
public abstract class SolrOperationsAdapter : ISolrOperationsAdapter
{
protected SolrOperationsAdapter()
{
}
public IEnumerable<Base> Execute()
{
return ExecuteImpl();
}
protected abstract IEnumerable<Base> ExecuteImpl();
}
public class GenericSolrOperationsAdapter<T> : SolrOperationsAdapter
{
private readonly ISolrOperations<T> _solrOperations;
public static ISolrOperationsAdapter From(ISolrOperations<T> solrOperations)
{
return new GenericSolrOperationsAdapter<T>(solrOperations);
}
protected GenericSolrOperationsAdapter(ISolrOperations<T> solrOperations)
: base()
{
_solrOperations = solrOperations;
}
//If you define interfaces you can return return IEnumerable<IInterface>
protected override IEnumerable<Base> ExecuteImpl()
{
//here you can somehow convert result of query to your types(Class1, Class2 or some interface behind)
return _solrOperations.Execute().ConvertTo<IEnumerable<Base>>();
}
}
用法示例:
ISolrOperations<Class1> solrOperations = new SolrOperationsImplementation()
ISolrOperationsAdapter adapter = GenericSolrOperationsAdapter<Class1>.From(solrOperations);
IEnumerable<Base> result = adapter.Execute();
将类包装在实现所需接口的通用适配器类中。
如果您要搜索它的示例,这称为适配器模式。
通用适配器的示例:
public class SomeGenericInterfaceAdapter<T> : INonGenericInterface
{
private IGenericInterface<T> _someGenericInterface;
public SomeGenericInterfaceAdapter(IGenericInterface<T> someGenericInterface)
{
_someGenericInterface = someGenericInterface;
}
public void SomeMethod()
{
_someGenericInterface.SomeMethod();
}
}
public interface INonGenericInterface
{
void SomeMethod();
}
public interface IGenericInterface<T>
{
void SomeMethod();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.