自参考界面 [英] Self referencing interface

查看:65
本文介绍了自参考界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想做的事情:

Interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever)
}

,以便实现此目标的类必须具有一个返回其自身类型列表的函数. 这有可能吗? 我知道-从技术上讲-一个实现此目标的类可以返回实现此目标的其他类的列表,不一定是同一类,但是即使它不是理想的,我也可以接受.

so that classes implementing this must have a function that returns a list of their own type. Is this even possible? I know that - technically - a class implementing this could return a list of other classes which implement this, not necessarily the same class, but I can live with that even though it isn't ideal.

我已经尝试过了,但是我无法获得实现类来正确实现该方法.

I have tried this, but I can't get the implementing class to correctly implement the method.

推荐答案

这对我有用:

public interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever);
}

public class Program : IMyInterface
{
    public string Member { get; set; }

    public List<IMyInterface> GetAll(string whatever)
    {
        return new List<IMyInterface>()
            { new Program() { Member = whatever } };
    }

    static void Main(string[] args)
    {
        List<IMyInterface> all = new Program().GetAll("whatever");
        Console.WriteLine(all.Count);
    }
}

这篇关于自参考界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆