根据子类从基类指定抽象方法的返回类型 [英] Specifying the return type of an abstract method from a Base Class according to a Sub Class

查看:36
本文介绍了根据子类从基类指定抽象方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

abstract class Base {
        public abstract List<...> Get(); //What should be the generic type?
}

class SubOne : Base {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base {
    public override List<SubTwo> Get() {

    }
}

我想创建一个抽象方法,该方法返回具体子类是什么类.因此,从示例中可以看出,SubOne 中的方法应该返回 ListSubTwo 中的方法应该返回 List.

I want to create an abstract method that returns whatever class the concrete sub class is. So, as you can see from the example, the method in SubOne should return List<SubOne> whereas the method in SubTwo should return List<SubTwo>.

我在基类中声明的签名中指定什么类型?

What type do I specify in the signature declared in the Base class ?

[更新]

感谢您发布的答案.

解决方案是使抽象类具有通用性,例如:

The solution is to make the abstract class generic, like such:

abstract class Base<T> {
        public abstract List<T> Get();
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {

    }
} 

推荐答案

你的抽象类应该是通用的.

Your abstract class should be generic.

abstract class Base<T> {
        public abstract List<T> Get(); 
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {
    }
}

如果需要引用没有泛型类型参数的抽象类,请使用接口:

If you need to refer to the abstract class without the generic type argument, use an interface:

interface IBase {
        //common functions
}

abstract class Base<T> : IBase {
        public abstract List<T> Get(); 
}

这篇关于根据子类从基类指定抽象方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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