我有一个现有的Generic界面,如下所示:
public interface IWorkflowValidator<T> where T : IPersistent, IStateful, new()
{
...
问题是我希望将这个通用接口作为另一个名为WorkflowService的类的属性或作为WorkflowService类构造函数中的属性。当我在下面的构造函数示例中这样做时,编译器会抱怨 - 我相信我遇到了T位问题(虽然我可能在那里出错)。
e.g。 WorkflowService构造函数
public WorkflowService(ControllerAccess controllerAccess, IValidationDictionary validatonDictionary, IWorkflowValidator<T> workflowValidator) where T: IPersistent, IStateful
{
答案 0 :(得分:2)
如果要在作为构造函数参数接受的IWorkflowValidator<T>
上设置泛型约束,则必须使类本身具有通用性,并将约束添加到类的泛型类型参数中,如下所示:
public interface IWorkflowValidator<T> where T : IPersistent, IStateful, new()
{
}
public class WorkflowService<T> where T : IPersistent, IStateful, new()
{
private readonly IWorkflowValidator<T> _validator;
public WorkflowService(IWorkflowValidator<T> validator)
{
_validator = validator;
}
public IWorkflowValidator<T> Validator
{
get { return _validator; }
}
}
答案 1 :(得分:1)
如果要将泛型接口传递给您的类,则必须将泛型参数添加到您的类中。
public interface IWorkflowValidator<T> where T : IPersistent, IStateful, new() { }
public class WorkflowService<T> where T: IPersistent, IStateful, new()
{
public WorkflowService(ControllerAccess controllerAccess, IValidationDictionary validatonDictionary, IWorkflowValidator<T> workflowValidator)
{ }
}
或者您可以创建非接口版本的接口(基础版为通用版本),并在创建实现接口通用版本的类实例时指定类型。
public interface IWorkflowValidator { }
public interface IWorkflowValidator<T> : IWorkflowValidator
where T : IPersistent, IStateful, new() { }
public class WorkflowService
{
public WorkflowService(ControllerAccess controllerAccess, IValidationDictionary validatonDictionary, IWorkflowValidator workflowValidator) { }
}