簡體   English   中英

C#Generic Constraint - 如何引用當前類類型?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM