[英]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.