在下面的示例控制檯應用程序的工作,你會發現,該程序試圖創建一個籃球隊,然後,添加球員和教練的球隊。如何使用泛型類型的泛型列表泛型類
應用程序的設計實現通用類(團隊和個人)的具體類(湖人(),播放器()和教練())將繼承。
程序拋出建立在點例外,我試圖將Person對象添加到列表team.Members。
異常讀取:
最好重載方法匹配 'System.Collections.Generic.List>。新增(人)' 具有一些無效 參數。
我不明白爲什麼編譯器不允許我到通用播放器(科比和菲爾)添加到成員列表成員時,被定義爲通用播放器的泛型列表。
你能解釋一下錯誤的原因,以及如何解決它?
此外,您還可以填補我在下面的示例程序是否是不典型的,我們應該如何實現仿製藥?換句話說,鑑於下面程序中的錯誤,這讓我想知道爲什麼我應該實現泛型,而不是堅持使用正常的抽象類。
順便說一句,請不要反對票,只是因爲你不喜歡湖人隊;)
class Program
{
static void Main(string[] args)
{
//Create a team
Team<Lakers> team = new Lakers();
//Create a player then add the player to the list of team members
Person<Player> p = new Player();
p.Name = "Kobe";
team.Members.Add(p); //Invalid argument exception here
//Create a coach then add the coach to the list of team members
Person<Coach> c = new Coach();
c.Name = "Phil";
team.Members.Add(c); //Invalid argument exception here
//Display the members of the team
team.Members.ForEach(n => Console.WriteLine(n.Name));
Console.ReadLine();
}
}
//A generic class containing a generic list of a generic type
abstract class Team<T>
{
public List<Person<T>> Members = new List<Person<T>>();
}
//A concrete basketball team
class Lakers : Team<Lakers>
{
}
//A generic class that represents a person
abstract class Person<T>
{
public string Name { get; set; }
}
//A concrete person that represents a basketball player
class Player : Person<Player>
{
}
//A concrete person that represents a basketball coach
class Coach : Person<Coach>
{
}
是,我是新來的,我自己的自定義泛型類的工作,我從來沒有意識到/認爲在類簽名(抽象類團隊)的指定整個類定義中的類型。我現在明白了「公開列表>成員=新列表>();」考慮到示例程序設計,實際上並不合邏輯。 –
Jed
2011-03-11 16:52:23