如何将不同的泛型类分配给同一个变量

时间:2018-03-03 06:45:09

标签: c# generics dynamic

我知道这个问题可能已被多次询问过,而且我的标题可能需要一些帮助,所以请在关注这个问题之后立即关闭这个问题......我不知道如何正确搜索答案。

我遇到的情况是变量可能需要保留ISolrOperations<Class1>的实例,或者它可能需要保存ISolrOperations<Class2>的实例。问题是没有接口的基本版本,所以没有类我可以将变量定义为(除了对象,它显然不了解ISolrOperations<T>的方法)能够举办任何一个班级。

所以我所知道的唯一解决方案是a)做一个if / else语句,我在一个块中用ISolrOperations<Class1>做我需要的一切,在另一个块中用ISolrOperations<Class2>做我需要的一切虽然每个块基本上都包含重复的代码。或者b)我可以使变量动态化,只是失去一些编译时验证我的代码。

我试图思考是否有某种方法可以创建一个具有非泛型基础的通用包装类。也许基地必须把它当作一个对象来对待但是使用反射......但是我们就像拧它一样;如果我必须解决这个问题,也可以使用动态关键字。

是否有更多&#34;正确&#34;设计模式来处理这种情况?或者我的选择基本上是在动态或编写大量代码之间,只是为了让自己觉得我正在做这些事情&#34;对&#34;动态是否真的是最实用的解决方案?

编辑:其实我不确定动态是否能解决这个问题:/

编辑2:没有...其他代码使用lambdas和变量需要转换它,我显然不知道在编译时要投射什么,以便不能工作。

1 个答案:

答案 0 :(得分:1)

虽然我不确定,但这种方法可能有所帮助。此方法使用适配器模式

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(); 
相关问题