Ani*_*ish 12 c# generics design-patterns factory
我有几个具体使用以下类型的接口
interface IActivity<T>
{
bool Process(T inputInfo);
}
Run Code Online (Sandbox Code Playgroud)
具体类如下
class ReportActivityManager :IActivity<DataTable>
{
public bool Process(DataTable inputInfo)
{
// Some coding here
}
}
class AnalyzerActivityManager :IActivity<string[]>
{
public bool Process(string[] inputInfo)
{
// Some coding here
}
}
Run Code Online (Sandbox Code Playgroud)
现在我怎样才能编写工厂类来重新调整通用接口,比如IActivity.
class Factory
{
public IActivity<T> Get(string module)
{
// ... How can i code here
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Ser*_*kiy 15
您应该创建泛型方法,否则编译器将不知道T返回值的类型.如果您将拥有,T您将能够根据以下类型创建活动T:
class Factory
{
public IActivity<T> GetActivity<T>()
{
Type type = typeof(T);
if (type == typeof(DataTable))
return (IActivity<T>)new ReportActivityManager();
// etc
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
IActivity<DataTable> activity = factory.GetActivity<DataTable>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9982 次 |
| 最近记录: |