首页 > 解决方案 > C# 抽象方法,只读属性

问题描述

我有一个任务(一堆 oop 的东西,多态性和继承),除此之外,我必须做以下事情:

  1. 我需要向 Vehicle 类添加一个抽象方法(称为calculateOccupancy()),它必须返回车辆中剩余空间的百分比。然后我必须在我的派生类中实现它。这里的问题是,我有 3 个派生类,其中两个有 2 个属性,一个有 3 个。那么我如何制作我的抽象方法,以便它可以接受 2 或 3 个参数。

  2. 我必须向 Person 类添加一个不可更改的属性,并且该属性必须返回姓名和姓氏的第一个字母,除以点。

namespace Example
{
    abstract class Vehicle
    { 
        //class member variables, most likely unnecessary for the questions
        private Person driver;
        private string vehicleBrand;
        private string vehicleType;
        private double fuelConsumption;
        private double gasTankSize;
        private string fuelType;

        //the default constructor
        public Vehicle()
        {}

        //The abstract method from question 2
        // how to make it so that it wont error when I need to 
        //put in 3 variables instead of two, meaning, how would I add int c
        public abstract double calculateOccupancy (int a, int b);

        //The derived class that implements the method
        class Bus : Vehicle
        {
            private int allSeats; 
            private int allStandingSeats; 
            private int busPassengers; //the number of passengers

            //the constructor
            public Bus (int a, int b, int c)
            {
                allSeats=a;
                allStandingSeats=b;
                busPassengers=c;
            }

            //the abstract method 
            // needs to take in int b (standing seats)
            public override double calculateOccupancy(int a, int c)
            {
                 //this code calculates the leftover space in the vehicle
                 double busSpace=(busPassengers*100) / allSeats;
                 return busSpace;

                 //same code for the leftover standing space (int c)
            } 
        }
    }

    class Person
    {
        protected string name;
        protected string lastName;
        //question 1
        //properties for char gender
        protected char gender;
        //question 3
        protected readonly string initials;

        //the code errors, at the get/set
        public char Gender
        {
            get{ return gender; }
            set {gender=value;}
        }

        /*and the property im not sure how to make
        public string Initials{}
        */
    }

我希望这些评论能增加一些清晰度,而不是混淆,谢谢大家的帮助。

标签: c#.netoopinheritanceproperties

解决方案


在创建抽象方法时给“可选”值一个值

public abstract double izracunajZasedenost (int a = -1, int b = -1) 
{
    if (a == -1){ 
        //do method with ignoring a
    }
};

推荐阅读