我有一個基類,它有一個抽象方法返回它自己的列表。不匹配的列表類型
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
{
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
什麼是有一個基類返回它自己的列表的最佳方法,重寫基類的方法,做同樣的事情?
正如在其他答案中提到的這個相同的建議,[這可能並不總是做你想做的事,或者認爲它確實如此。](http://blogs.msdn.com/b/ericlippert/archive/2011/ 02/03/curiouser-and-curiouser.aspx) – Servy 2012-08-13 19:59:18
只是牢記SOLID,一切都很好 – GSerjo 2012-08-13 20:08:30
你看起來像這個解決方案是非常優越的,當它不是。這實際上很有缺陷。它可以在不引起這些問題的情況下使用,當然,對於幾乎所有的設計/模式都是如此。 – Servy 2012-08-13 20:12:36