[英]Factory class returning a generic interface
I have few concrete which uses the following type of interface 我有几个具体使用以下类型的接口
interface IActivity<T>
{
bool Process(T inputInfo);
}
Concrete classes are like as follows 具体类如下
class ReportActivityManager :IActivity<DataTable>
{
public bool Process(DataTable inputInfo)
{
// Some coding here
}
}
class AnalyzerActivityManager :IActivity<string[]>
{
public bool Process(string[] inputInfo)
{
// Some coding here
}
}
Now how can i write the factory class which retuns a generic interface some thing like IActivity. 现在我怎样才能编写工厂类来重新调整通用接口,比如IActivity。
class Factory
{
public IActivity<T> Get(string module)
{
// ... How can i code here
}
}
Thanks 谢谢
You should create generic method, otherwise compiler will not know type of T
in return value. 您应该创建泛型方法,否则编译器将不知道返回值中的T
类型。 When you will have T
you will be able to create activity based on type of T
: 如果你有T
你将能够根据T
类型创建活动:
class Factory
{
public IActivity<T> GetActivity<T>()
{
Type type = typeof(T);
if (type == typeof(DataTable))
return (IActivity<T>)new ReportActivityManager();
// etc
}
}
Usage: 用法:
IActivity<DataTable> activity = factory.GetActivity<DataTable>();
Often this is implemented as in lazyberezovsky's answer . 通常这是在lazyberezovsky的答案中实现的 。 In c++ you could use template specialization to get compiler errors when you try to create a type the factory does not handle. 在c ++中,当您尝试创建工厂不处理的类型时,您可以使用模板特化来获取编译器错误。
You can't do that in C# but you can get close. 你不能在C#中做到这一点,但你可以接近。 Though the code might look a little surprising which in turn could be a problem. 虽然代码可能看起来有点令人惊讶,反过来可能是一个问题。
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;
}
}
The usage would then be 那么用法就是
IActivity<someType> act = Factory.Creator<someType>().Get();
of course this only works if you can pass a concrete type. 当然,只有你可以传递具体类型才有效。 If you need to pass a type parameter things get more complicated. 如果你需要传递一个类型参数,事情会变得更复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.