[英]C# Generic Constraint - How to refer to current class type?
我有以下类/接口:
public abstract class AbstractBasePresenter<T> : IPresenter<T>
where T : class, IView
{
}
public interface IPresenter<T>
{
}
public interface IView<TV, TE, TP> : IView
where TV : IViewModel
where TE : IEditModel
//where TP : AbstractBasePresenter<???>
{
}
public interface IView {}
有什么方法可以限制TP在IView <>上的TP是一个继承自AbstractBasePresenter的类吗?
或者是我唯一的选择,创建一个非通用的IPresenter接口,然后更新IPresenter来实现它,然后使用检查“TP:IPresenter”?
谢谢
更新:
以下建议的答案不起作用:
public interface IView<TV, TE, TP> : IView
where TV : IViewModel
where TE : IEditModel
where TP : AbstractBasePresenter<IView<TV,TE,TP>>
{
}
我将接口声明为:
public interface IInsuredDetailsView : IView<InsuredDetailsViewModel, InsuredDetailsEditModel, IInsuredDetailsPresenter>
{ }
public interface IInsuredDetailsPresenter : IPresenter<IInsuredDetailsView>
{ }
编译器抱怨IInsuredDetailsPresenter不能分配给AbstractBasePresenter>
没问题,不需要另一个通用参数:
public interface IView<TV, TE, TP> : IView
where TV : IViewModel
where TE : IEditModel
where TP : AbstractBasePresenter<IView<TV,TE,TP>>
{
}
编辑:更新的问题:
如果您不需要演示者从AbstractBasePresenter继承,请将代码更改为:
public interface IView<TV, TE, TP> : IView
where TV : IViewModel
where TE : IEditModel
where TP : IPresenter<IView<TV,TE,TP>>
{
}
您可以这样做,但是您需要为IView<>
接口提供另外一个类型参数:
public interface IView<TV, TE, TP, T> : IView
where TV : IViewModel
where TE : IEditModel
where TP : AbstractBasePresenter<T>
where T : class, IView
{
}
编辑:
根据您的问题中的版本: IInsuredDetailsPresenter
绝对不能分配给AbstractBasePresenter
。 由于您在原始问题中要求的约束,编译器正在抱怨。 更具体地说,由于这一部分
where TP : AbstractBasePresenter<T>
看来你想要将TP
限制为一个接口。 您可以尝试以下代码:
public interface IView<TV, TE, TP, T> : IView
where TV : IViewModel
where TE : IEditModel
where TP : IPresenter<T>
{
}
不再需要对T
约束,因为IPresenter<T>
没有。 当然,你可以用类似的方式调整armen.shimoon的答案。 关键是用IPresenter<T>
约束替换AbstractBasePresenter<T>
IPresenter<T>
约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.