[英]How to create a generic factory returning different interface types and an abstract class
[英]Factory class returning a generic interface
我有幾個具體使用以下類型的接口
interface IActivity<T>
{
bool Process(T inputInfo);
}
具體類如下
class ReportActivityManager :IActivity<DataTable>
{
public bool Process(DataTable inputInfo)
{
// Some coding here
}
}
class AnalyzerActivityManager :IActivity<string[]>
{
public bool Process(string[] inputInfo)
{
// Some coding here
}
}
現在我怎樣才能編寫工廠類來重新調整通用接口,比如IActivity。
class Factory
{
public IActivity<T> Get(string module)
{
// ... How can i code here
}
}
謝謝
您應該創建泛型方法,否則編譯器將不知道返回值中的T
類型。 如果你有T
你將能夠根據T
類型創建活動:
class Factory
{
public IActivity<T> GetActivity<T>()
{
Type type = typeof(T);
if (type == typeof(DataTable))
return (IActivity<T>)new ReportActivityManager();
// etc
}
}
用法:
IActivity<DataTable> activity = factory.GetActivity<DataTable>();
通常這是在lazyberezovsky的答案中實現的 。 在c ++中,當您嘗試創建工廠不處理的類型時,您可以使用模板特化來獲取編譯器錯誤。
你不能在C#中做到這一點,但你可以接近。 雖然代碼可能看起來有點令人驚訝,反過來可能是一個問題。
public static class Factory {
public static IActivity<someType> Get(this someType self){
//stuff specific to someType
}
public static IActivity<someOtherType> Get(someOtherType self){
//stuff specific to someOtherType
}
public static T Creator<T>(){
return null;
}
}
那么用法就是
IActivity<someType> act = Factory.Creator<someType>().Get();
當然,只有你可以傳遞具體類型才有效。 如果你需要傳遞一個類型參數,事情會變得更復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.