我有一个基类,它有一个抽象方法,该方法返回自身的列表。
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/