C# 不匹配的列表类型
我有一个基类,它有一个抽象方法,返回它自己的列表C# 不匹配的列表类型,c#,list,generics,overriding,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();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class baseclass
{
public abstract List<baseclass> somemethod();
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间控制台应用程序1
{
公共抽象类基类
{
公共摘要列表方法();
}
}
以及试图通过返回*it*self的列表来重写基类方法的子体
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间控制台应用程序1
{
类childclass:baseclass
{
公共重写列表方法()
{
列表结果=新列表();
结果。添加(新的子类(“测试”));
返回结果;
}
公共子类(字符串描述)
{
描述=描述;
}
公共字符串描述;
}
}
但我得到了这个错误:
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
错误1“ConsoleApplication1.childclass.somemethod()”:
返回类型必须为“System.Collections.Generic.List”
要匹配重写的成员“ConsoleApplication1.baseclass.somemethod()”
C:\Users\josephst\AppData\Local\Temporary Projects\ConsoleApplication1childclass.cs
0 42控制台应用程序1
让基类返回自己的列表,重写执行相同操作的基类方法的最佳方法是什么?重写方法时,重写方法的签名必须与被重写方法的签名完全匹配。您可以通过泛型实现您想要的:
public abstract class BaseClass<T>
{
public abstract List<T> SomeMethod();
}
public class ChildClass : BaseClass<ChildClass>
{
public override List<ChildClass> SomeMethod() { ... }
}
公共抽象类基类
{
公共摘要列表方法();
}
公共类子类:基类
{
公共重写列表SomeMethod(){…}
}
错误消息是不言自明的。要覆盖该方法,您需要返回一个列表
public覆盖列表somemethod()
{
列表结果=新列表();
结果。添加(新的子类(“测试”));
返回结果;
}
泛型是很好的解决方案,但不要使用公共抽象列表somemethod()这是个坏习惯
你应该使用
公共抽象类基类
{
受保护的抽象列表DoSomeMethod();
公共列表方法()
{
返回DoSomeMethod();
}
}
公共类子类:基类
{
受保护的覆盖列表DoSomeMethod(){…}
}
不会公开抽象列出SomeMethod(),其中t:BaseClass代码>帮助?这解决了问题,但我希望返回的列表具有特定于我的子类的值。@JosephStyons:您可以返回一个列表
,如上所示。但是,如果要覆盖该方法,则该方法签名必须返回一个列表。您可以将基类
转换为子类
。正如在另一个答案中提到的,您使用相同的建议,使它看起来像是这个解决方案非常优越,而实际上它并不是。事实上,它有很大的缺陷。当然,它可以在不引起这些问题的情况下使用,但实际上每种设计/模式都是如此。同意,这是价格和解决方案的平衡
public abstract class BaseClass<T>
{
public abstract List<T> SomeMethod();
}
public class ChildClass : BaseClass<ChildClass>
{
public override List<ChildClass> SomeMethod() { ... }
}
public override List<baseclass> somemethod()
{
List<childclass> result = new List<childclass>();
result.Add(new childclass("test"));
return result;
}
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(){ ... }
}