期望从类 A 和接口 B 实现的对象 - 任何强制实现的选项/模式

本文关键字:实现 任何强 选项 模式 对象 接口 期望 | 更新日期: 2023-09-27 18:35:53

>情况:

我正在使用Monotouch进行iOS开发(C#),其中一个主要类是UIViewController。iOS 库(或第三方)中有很多现有的类从中实现,并且还有很多函数调用返回 UIViewController 对象。

我现在创建了一个抽象函数,它应该在子类中实现,它必须返回一个"带有页码参数的 UIView控制器"。

有以下抽象方法(我的方法):

public abstract PageViewController GetPageViewController(int pageNumber);

跟:

public class PageViewController: UIViewController{
        public int PageNumber = 0;
            ...

所以我得到了一个UIView控制器,它有一个"PageNumber"参数(正是我需要的)。创建UIViewController时,我从"PageViewController"而不是"UIViewController"派生。

我的问题:

iOS 有很多从 UIViewController 派生的子类。例如,UICollectionViewController。

如果我想使用"UICollectionViewController",我不能从"PageViewController"派生,因为它没有在"UICollectionViewController"中实现的附加功能。

唯一的方法是将"PageViewController"更改为

public class PageViewController: UICollectionViewController{

但是,如果我需要传递UIViewController的另一个子类,我又被卡住了。

创建包含两个参数(UIViewController 和 PageNumber)的对象也是不可能的,因为 UIViewController 将由 iOS 使用,当我稍后从 iOS 取回 UIViewController 对象时,我需要能够检索页码。

利用我目前的知识拥有"某些东西"的唯一方法是:

1) 更改

public abstract PageViewController GetPageViewController(int pageNumber);

public abstract UIViewController GetPageViewController(int pageNumber);

这将确保你可以传递"任何"UIViewController(包括所有子类)

2)使用参数 PageNumber 定义接口(例如 IPageNumber)

3)您应该传递UIViewController的文档,该控制器也实现了此附加接口

4)当 UIViewController 在某个时间点返回时,请检查它是否也是"IPageNumber"。如果没有,请抛出错误。

当然,这将在运行时而不是在编译时引发错误。

有谁知道这个问题是否有更好的解决方案?

PS:我是一个没有经验的业余开发人员,所以我的一些术语不正确,请道歉。我也搜索过,但找不到任何东西(也是因为我不知道要搜索的好关键字)

期望从类 A 和接口 B 实现的对象 - 任何强制实现的选项/模式

为什么不直接使用接口呢?喜欢:

public interface IPageViewController
{
    int PageNumber { get; }
}

制定UIViewControllerUICollectionViewController实现它:

public class PageViewController: UIViewController, IPageViewController
{
    public int PageNumber { get; private set; }
    ...
}