简体   繁体   中英

C# Generic Constraint - How to refer to current class type?

I have the following classes/interfaces:

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 {}

Is there any way that I can constrain TP on IView<> to be a class that inherits from AbstractBasePresenter?

Or is my only alternative to create a non-generic IPresenter interface and then update IPresenter to implement it and then use check "TP : IPresenter"?

Thanks

Update:

Proposed answer below does not work:

public interface IView<TV, TE, TP> : IView
where TV : IViewModel
where TE : IEditModel
where TP : AbstractBasePresenter<IView<TV,TE,TP>>
{
}

I have interface declared as:

public interface IInsuredDetailsView : IView<InsuredDetailsViewModel, InsuredDetailsEditModel, IInsuredDetailsPresenter>
{ }

public interface IInsuredDetailsPresenter : IPresenter<IInsuredDetailsView>
{ }

Compiler complains that IInsuredDetailsPresenter is not assignable to AbstractBasePresenter>

No problem, no need for another generic parameter:

public interface IView<TV, TE, TP> : IView
    where TV : IViewModel
    where TE : IEditModel
    where TP : AbstractBasePresenter<IView<TV,TE,TP>>
{
}

Edit: Updated question:

If you do not need the presenter to inherit from AbstractBasePresenter, change the code to:

public interface IView<TV, TE, TP> : IView
    where TV : IViewModel
    where TE : IEditModel
    where TP : IPresenter<IView<TV,TE,TP>>
{
}

You can do it, but you need to provide one more type argument to the IView<> interface:

public interface IView<TV, TE, TP, T> : IView
    where TV : IViewModel
    where TE : IEditModel
    where TP : AbstractBasePresenter<T>
    where T : class, IView
{
}

Edit:

According to editions in your question: IInsuredDetailsPresenter is definitely not assignable to AbstractBasePresenter . Compiler is complaining due to the constraint you requested in your original question. More specifically due to this part

where TP : AbstractBasePresenter<T>

It seems you want to constrain TP to be an interface as well. You may try the below piece of code:

public interface IView<TV, TE, TP, T> : IView
    where TV : IViewModel
    where TE : IEditModel
    where TP : IPresenter<T>
{
}

Constraints on T are no more needed, because IPresenter<T> has none. Of course, you could adapt armen.shimoon's answer in a similar manner. The point is to replace AbstractBasePresenter<T> constraint with IPresenter<T> constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM