c# - 不匹配的列表类型

标签 c# list generics overriding

我有一个基类,它有一个抽象方法,该方法返回自身的列表。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public abstract class baseclass
    {
        public abstract List<baseclass> somemethod();        
    }
}

以及一个试图通过返回 *it*self 列表来重写基类方法的后代。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class childclass : baseclass
    {
        public override List<childclass> somemethod()
        {
            List<childclass> result = new List<childclass>();
            result.Add(new childclass("test"));
            return result;
        }

        public childclass(string desc)
        {
            Description = desc;
        }

        public string Description;
    }
}

但我收到此错误:

Error   1   'ConsoleApplication1.childclass.somemethod()':
return type must be 'System.Collections.Generic.List<ConsoleApplication1.baseclass>'
to match overridden member 'ConsoleApplication1.baseclass.somemethod()' 
C:\Users\josephst\AppData\Local\Temporary Projects\ConsoleApplication1childclass.cs 
0   42  ConsoleApplication1

让基类返回自身列表并重写执行相同操作的基类方法的最佳方法是什么?

最佳答案

通用是很好的解决方案,但不要使用 public abstract List<baseclass> somemethod();这是不好的做法

您应该使用non-virtual interface pattern

public abstract class BaseClass<T>
{
    protected abstract List<T> DoSomeMethod();

    public List<T> SomeMethod()
    {
        return DoSomeMethod();
    }
}

public class ChildClass : BaseClass<ChildClass>
{
    protected override List<ChildClass> DoSomeMethod(){ ... }
}

关于c# - 不匹配的列表类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940898/

相关文章:

python - 从单词列表创建三元组

jQuery 无法删除列表元素

c# - MethodBody.LocalVariables 计数令人困惑

c# - 哪个 JIT 正在运行我的应用程序

c# - DhtmlX 甘特图未获得正确的链接目标 ID

algorithm - 给定一个列表列表,返回一个具有列表长度的列表(在另一个列表中)

java - 为什么Java泛型不能用于静态方法?

typescript - 如何从装饰器中的装饰属性解析属性值的通用类型

java - 为什么 Comparable 自然排序需要和 equals 方法保持一致?

c# - Caliburn micro 将 message.attach 指向所需的 View 模型