我正在自学 C#,并且有一个关于从父对象的特定实例继承的问题。
例如,如果我这样定义我的类:
class League
{
public string name { get; set; }
}
class Player : League
{
public Guid PlayerGuid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Team : Player
{
public Guid TeamGuid { get; set; }
public string TeamName { get; set; }
}
然后像这样实例化类:
static void Main(string[] args)
{
League myLeague = new League() { name = "The League" };
Player taco = new Player() { PlayerGuid = Guid.NewGuid(), FirstName = "Taco", LastName = "MacArthur" };
Player pete = new Player() { PlayerGuid = Guid.NewGuid(), FirstName = "Pete", LastName = "Eckhart" };
Team tacoTeam = new Team() { TeamGuid = Guid.NewGuid(), TeamName = "Password is Taco" };
Team peteTeam = new Team() { TeamGuid = Guid.NewGuid(), TeamName = "3-Pete" };
}
如何确保 Team tacoTeam 继承自 Player taco 而 Team peteTeam 继承自 Player pete?
我的感觉是,我不了解如何为这种情况正确定义类,并且希望能得到有关如何完成此操作的指针。
为了澄清元素的关系,我将“玩家”更改为“所有者”更好地代表了我的想法。我可以进一步为“玩家”添加一个类来代表真正的玩家而不是扶手椅玩家。
通过@neoistheone 和@McGarnagle 的输入,我能够修改它并这样定义类:
class League
{
public string name { get; set; }
}
class Owner
{
public Guid OwnerGuid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Team
{
public Guid TeamGuid { get; set; }
public string TeamName { get; set; }
public Owner TeamOwner { get; set; }
public League League { get; set; }
}
然后我可以创建类的一个实例并从中得到什么:
static void Main(string[] args)
{
League MyLeague = new League() { name = "The League" };
Owner taco = new Owner() { FirstName = "Taco", LastName = "MacArthur", OwnerGuid = Guid.NewGuid() };
Owner pete = new Owner() { FirstName = "Pete", LastName = "Eckhart", OwnerGuid = Guid.NewGuid() };
Team tacoTeam = new Team() { TeamGuid = Guid.NewGuid(), TeamName = "Password is Taco", League = MyLeague, TeamOwner = taco };
Team peteTeam = new Team() { TeamGuid = Guid.NewGuid(), TeamName = "3-Pete", League = MyLeague, TeamOwner = pete };
List<Team> Teams = new List<Team>();
Teams.Add(tacoTeam);
Teams.Add(peteTeam);
foreach(Team team in Teams){
Console.WriteLine("Team Name:\t{0}\nTeam Owner:\t{1}\nLeague Name:\t{2}\n-----",
team.TeamName, team.TeamOwner.FirstName + " " + team.TeamOwner.LastName, team.League.name);
}
Console.ReadLine();
}
这似乎在帮助对我的代码中的数据进行建模方面做得相当不错,以使其更容易进出我正在使用此应用程序开发的数据库。