我有一个像这样的通用接口:
public interface IHandler
{
T Process<T>(IProcess process) where T : new();
}
有时我想具体实现接口,例如:
public class BoolHandler : IHandler
{
public bool Process<bool>(IProcess process)
{
// Do some work - set to true or false
return true;
}
}
这可能吗?
编辑:
目前我可以做到这一点:
// Injecct handler in Main and work with single handler
ViewModel model = handler.Process<ViewModel>(process);
DifferentModel model = handler.Process<DifferentModel >(process);
根据列出的建议,我将必须执行此操作(这是我要避免的操作,这需要我即时创建一堆处理程序):
IHandler<ViewModel> handler = new Handler<ViewModel>();
ViewModel viewModel = handler.Process(process);
IHandler<DifferentModel> handler = new Handler<DifferentModel>(); // Create yet another handler - arrr
DifferentModel viewModel = handler.Process(process);
最佳答案
据我从注释交流中了解到的问题,一些处理程序可以处理任何类型的T
(或许多类型T
),而其他处理程序只能处理一种类型。另外,您想在一个使用者中多态使用这些处理程序。
您可以执行以下操作:
创建两个这样的接口:
public interface IHandler //Can handle many types
{
T Process<T>(int process);
bool CanProcess<T>();
}
public interface IHandler<T> //Can handle a single type
{
T Process(int process);
}
然后像这样从
IHandler<T>
到IHandler
创建一个适配器:public class Adaptor<T> : IHandler
{
private readonly IHandler<T> handler;
public Adaptor(IHandler<T> handler)
{
this.handler = handler;
}
public T1 Process<T1>(int process)
{
if(!CanProcess<T1>())
throw new Exception(
"Contract violated. I cannot handle type " + typeof(T1).Name);
return (T1)(object)handler.Process(process);
}
public bool CanProcess<T1>()
{
return typeof (T1) == typeof (T);
}
}
现在,您的复合材料可以执行以下操作:
public class CompositeHandler : IHandler
{
private readonly IHandler[] handlers;
public CompositeHandler(params IHandler[] handlers)
{
this.handlers = handlers;
}
public T Process<T>(int process)
{
var handler = handlers.FirstOrDefault(h => h.CanProcess<T>());
if(handler == null)
throw new Exception(
"Contract violated. I cannot handle type " + typeof(T).Name);
return handler.Process<T>(process);
}
public bool CanProcess<T>()
{
return handlers.Any(h => h.CanProcess<T>());
}
}
现在,您可以将任何
IHandler<T>
实现改编为IHandler
并将其通常用作IHandler
。例如,您可以将其用作复合材料的一部分。这是一个示例组成:
var service = new CompositeHandler(
new TypeThatImplementsTheNonGenericInterface(),
new Type2ThatImplementsTheNonGenericInterface(),
new Adaptor<SomeType>(
new TypeThatImplementsTheGenericInterface<SomeType>()));