c# - C# 抽象方法,只读属性
问题描述
我有一个任务(一堆 oop 的东西,多态性和继承),除此之外,我必须做以下事情:
我需要向 Vehicle 类添加一个抽象方法(称为calculateOccupancy()),它必须返回车辆中剩余空间的百分比。然后我必须在我的派生类中实现它。这里的问题是,我有 3 个派生类,其中两个有 2 个属性,一个有 3 个。那么我如何制作我的抽象方法,以便它可以接受 2 或 3 个参数。
我必须向 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{}
*/
}
我希望这些评论能增加一些清晰度,而不是混淆,谢谢大家的帮助。
解决方案
在创建抽象方法时给“可选”值一个值
public abstract double izracunajZasedenost (int a = -1, int b = -1)
{
if (a == -1){
//do method with ignoring a
}
};
推荐阅读
- python-3.x - django check_password 使用正确的密码返回 false
- c# - 在 asp:Gridview 中缺少 Header 左侧的垂直边框
- javascript - 让文本在 'flex-shrink-0' (TailwindCSS) 内动态收缩
- c# - bbb-install:您必须在 Ubuntu 16.04 服务器上运行此命令
- android - Firebase 查询中带有 limitToLast() 的 endAt() 在 android 中无法按预期工作
- loops - 使用C语言中的Loops,如果用户输入元音并且输入的字符数已经达到10,则循环将终止
- javascript - 如何将控制器中 JsonResult 的数据作为 JS 处理
- transactions - Spanner 模拟器 - 挂起交易
- javascript - Jquery:在 Chrome 中工作但在 Firefox 中不工作的代码
- c# - C#序列化没有“key”和“value”关键字的字典