赞
踩
本文仅作学习笔记与交流,不作任何商业用途,作者能力有限,如有不足还请斧正
本系列旨在通过补全学习之后,给出任意类图都能实现并做到逻辑上严丝合缝
Q:为什么要单讲继承字段与属性,不讲继承方法了吗???
A:因为继承方法离不开多态,多态相对于继承又是新的内容,容易混淆概念
在 C# 中,继承是面向对象编程的一个重要概念。它允许一个类(子类)从另一个类(父类)继承属性和方法,从而实现代码的重用和扩展
大大大前提是,你需要让父类和子类在同一命名空间,就比如:
首先,对于继承的字段等可以采用protected修饰符保证访问权限和安全性
C# & Unity 面向对象补全计划 之 访问修饰符-CSDN博客
其次,继承而来的字段可以在子类的构造函数,方法等中使用
除非是静态字段,不然无法给子类的字段赋值,别犯傻
使用栗子:
比如我现在有一个房子类,其有两个字段:标准地基长度,标准地基宽度
商业住房和住宅住房基于房子的标准地基长款进行修改
房子类:
- class Houes {
- protected int baseSubgradeLength;
- protected int baseSubgradeWeigth;
- public Houes() {
-
- baseSubgradeLength = 100;
- baseSubgradeWeigth = 100;
- }
-
- }
住宅和商业地基的继承与修改
- Dwelling dwelling = new Dwelling();
- Commerce commerce =new Commerce();
-
- class Houes {
- protected int baseSubgradeLength;
- protected int baseSubgradeWeigth;
- public Houes() {
-
- baseSubgradeLength = 100;
- baseSubgradeWeigth = 100;
- }
-
- }
- class Dwelling : Houes {
-
- public Dwelling() {
- Console.WriteLine("{0}{1}", baseSubgradeLength += 50, baseSubgradeWeigth += 50);
-
-
- }
-
- }
- class Commerce : Houes {
-
- public Commerce() {
-
- Console.WriteLine("{0}{1}", baseSubgradeLength += 100, baseSubgradeWeigth += 100);
- }
- }
现在,为了房子地基的字段更加安全,有关部门设置为私有变量,只给出属性接口去修改
商业类和住宅类还是想修改地基长宽,应该怎么办?
- class Houes {
- private int baseSubgradeLength;
- private int baseSubgradeWeigth;
- public Houes() {
-
- baseSubgradeLength = 100;
- baseSubgradeWeigth = 100;
- }
- protected int SubgradeL
- {
- get => baseSubgradeLength;
- set => baseSubgradeLength = value;
-
- }
- protected int SubgradeWeigth
- {
- get=> baseSubgradeWeigth;
- set => baseSubgradeWeigth = value;
- }
-
- }
还是像字段一样,在构造函数里直接通过继承来的属性访问器修改就行了
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- Dwelling dwelling = new Dwelling();
- dwelling.
- Commerce commerce =new Commerce();
-
- class Houes {
- private int baseSubgradeLength;
- private int baseSubgradeWeigth;
- public Houes() {
-
- baseSubgradeLength = 100;
- baseSubgradeWeigth = 100;
- }
- protected int SubgradeL
- {
- get => baseSubgradeLength;
- set => baseSubgradeLength = value;
-
- }
- protected int SubgradeWeigth
- {
- get=> baseSubgradeWeigth;
- set => baseSubgradeWeigth = value;
- }
-
- }
- class Dwelling : Houes {
-
-
- public Dwelling() {
-
- Console.WriteLine("{0}{1}", SubgradeL += 50, SubgradeWeigth += 50);
- }
-
- }
- class Commerce : Houes {
-
- public Commerce() {
-
-
- Console.WriteLine("{0}{1}", SubgradeL += 100, SubgradeWeigth += 100);
- }
- }
好了,现在字段和属性部分你驾轻就熟了,下一篇文章就是关于继承方法了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。