簡體   English   中英

返回實現變體接口的類

[英]Returning a class that implements a variant interface

背景:

我有三個Silverlight頁面,它們實現了我的界面:

interface IPageWithData<in T> where T : Entity
{
    void SetData(T obj);
}

public class APage : Page, IPageWithData<AItem> { /* Implementation */ }
public class BPage : Page, IPageWithData<BItem> { /* Implementation */ }
public class CPage : Page, IPageWithData<CItem> { /* Implementation */ }

// AItem, BItem and CItem are (EF) Entities (they are derived from Entity class).

然后,我使用一個自定義管理器,該管理器返回一個頁面,該頁面與作為參數提供的treeview節點相關:

private static class PageContainerHelper
{
    public static IPageWithData<Entity> SetPage(RadTreeViewItem selectedNode)
    {
        APageRTVI aNode = selectedNode as APageRTVI;
        BPageRTVI bNode = selectedNode as BPageRTVI;
        CPageRTVI cNode = selectedNode as CPageRTVI;

        if (aNode != null)
        {
            if (APage == null)
                APage = new APage();

            APage.SetData(aNode.aItem);
            return APage; // ERROR HERE
        }

        /*
            ... the same for BPageRTVI and CPageRTVI
        */
    }

    public static APage APage { get; set; }
    public static BPage BPage { get; set; }
    public static CPage CPage { get; set; }
}

問題:

我似乎錯誤地理解了co / contravariance。 SetPage()方法不允許我返回APage

無法將類型'MyProject.Views.Pages.APage'隱式轉換為'MyProject.Views.Pages.IPageWithData' 存在顯式轉換(您是否缺少演員表?)

APage實現IPageWithData<T> (盡管T具有更多派生類型)。 為什么這需要顯式轉換? 顯式轉換在這里是否還能工作?

因此,基本上,我需要兩件事。 一種是SetPage返回頁面時,它可以使用實現IPageWithData的類型的頁面,該類型的類型比Entity派生的更多。 我需要做的另一件事是IPageWithData<T>.SetData方法能夠接收類型比T派生得多的參數,即Entity

這可能嗎?

考慮您可以使用IPageWithData<Entity>做什么。 你可以做:

IPageWithData<Entity> pageWithData = PageContainerHelper.SetPage(...);
BItem item = new BItem();
pageWithData.SetData(item);

現在, 實現是一個APage您希望它與BItem一起使用嗎? 我懷疑你不想那樣。

換句話說,編譯器確實在做應做的事情-它可以保護您避免將錯誤類型的數據發送到無法處理的頁面。 我真的不知道如何解決此問題-我懷疑您也希望SetPage是通用的:

public static IPageWithData<T> SetPage<T>(RadTreeViewItem selectedNode)
    where T : Entity

但我不清楚這對您的實施有什么影響。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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