简体   繁体   English

基类和派生类

[英]base and derived classes

If I have Person class which will handle all common properties 如果我有Person类,它将处理所有常见属性

Person.cs

public class Person
{
   public FirstAndLastName {get; set;}
   public Health Health {get; set;}
   public Personality Personality {get; set;}
}

now I will need Player objects and later on different types of players (soccerPlayer, bballplayer, etc.) Since player is a person can I use this approach 现在,我将需要Player对象,并且稍后需要使用不同类型的玩家(soccerPlayer,bballplayer等)。由于玩家是一个人,因此我可以使用这种方法

Player.cs
public class Player:Person
{
   public Sport Sport {get; set;}
}

Now I want to implement some sport based player unique properties like: in basketball alley up , or volley shoot in football (soccer). 现在,我想实现一些基于运动的球员特有的属性,例如:在篮球小巷中或在足球中打排球(足球)。 You've got the pic. 你有照片。

Basketball.cs
public class Basketball:Player
{
   public int AlleyUpLevel {get; set;}
}

Question: is this proper way of creating base and derived classes, should my basketball player have access to all properties defined in Person class ? 问题:这是创建基类和派生类的正确方法,我的篮球运动员是否应该可以访问Person类中定义的所有属性? Thanks 谢谢

This is the correct way to create base and derived classes. 这是创建基类和派生类的正确方法。 Because your class Basketball inherits from Player which inherits from Person , Basketball will indeed have access to everything defined in Person that is marked public or protected . 由于您的Basketball类继承自Player类,而Player类又继承自Person ,因此, Basketball确实可以访问Person中定义的标记为publicprotected Anything marked private will not be accessible to inheriting classes. 任何标记为private东西都不能被继承的类访问。 Also keep in mind that in the case of many constructs such as fields and methods, the lack of an access modifier will default to a private access level. 还请记住,在许多构造(例如字段和方法)的情况下,缺少访问修饰符将默认为private访问级别。

Since your properties are all public , anyone , not just those deriving from Person , has access to both getting and setting the value of the property. 由于您的财产都是public ,因此任何人 ,不仅是从Person派生的财产,都有权获取和设置财产的价值。

You could consider making the setter private or protected , as in 您可以考虑将设置器设为privateprotected ,例如

public Personality Personality { get; protected set; }

The keyword protected means "only access from the containing class and from classes deriving from the containing class". 关键字protected意思是“只能从包含的类和从包含的类派生的类进行访问”。 On the other hand private means "only access from the containing class/struct". 另一方面, private表示“仅从包含的类/结构中访问”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM