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

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

问题描述

我有以下结构:

 抽象类基地{
公共抽象列表< ...>得到(); //应该是什么泛型类型?
}

类子一:基{
公众覆盖列表<&子一GT;获得(){

}
}

类子二:基{
公众覆盖列表<&子二GT;获得(){

}
}



我要创建一个返回任何类的具体子类是一个抽象的方法。所以,你可以看到的例子,在子一的方法应该返回列表<子一> 而在方法子二应该返回列表<子二方式>



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






[更新]



感谢您对张贴的答案。



解决的办法是使抽象类通用的,像这样的:

 抽象类基地< T> {
公共抽象列表< T>得到();
}

类子一:基础<&子一GT; {
公众覆盖列表<&子一GT;获得(){

}
}

类子二:基<&子二GT; {
公众覆盖列表<&子二GT;获得(){

}
}


解决方案

您抽象类应该是通用的。

 抽象类基地< T> {
公共抽象列表< T>得到();
}

类子一:基础<&子一GT; {
公众覆盖列表<&子一GT;获得(){

}
}

类子二:基<&子二GT; {
公众覆盖列表<&子二GT;获得(){
}
}

如果您需要参考抽象类没有泛型类型参数,使用接口:

 接口IBase的{
//常用功能
}

抽象类基地< T> :IBase的{
公共抽象列表< T>得到();
}


I have the following structure:

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() {

    }
}

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 ?


[UPDATE]

Thank you for the posted answers.

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天全站免登陆