我通过省略 totalFee 字段成功编译并运行了下面的源代码。如何将 totalFee 写入该程序,以便准确计算每项工作的总费用(费率 * 时间)?下面,你会看到我尝试使用一种方法;这产生了错误 CS0051(不一致的可访问性:参数类型 'Job' 比方法 'AddJobs.TotalPay(Job)' 更难访问)。
此源代码是对以下分配的响应:
“为 Harold 的家庭服务设计一个工作类。该类包含四个数据字段——工作描述(例如,“清洗窗户”)、完成工作的时间(例如,3.5)、每小时收费工作(例如,25.00 美元)和工作的总费用(每小时费率乘以小时数)。包括用于获取和设置除总费用之外的每个字段的属性 - 该字段将是只读的,并且每次都会计算其值设定小时费或小时数。重载 + 运算符,以便可以添加两个作业。两个作业的总和是一个新作业,其中包含两个原始作业的描述(用“和”连接)、原始作业的时间总和以及原始作业的平均小时费率。编写一个 Main() 函数来演示所有方法都能正常工作。将文件另存为 DemoJobs.cs。”
Microsoft® Visual C#® 2008,面向对象编程简介,3e,Joyce Farrell
这是源代码:
using System;
public class AddJobs
{
private double totalFee;
public AddJobs(double totalFee)
{
TotalFee = totalFee;
}
public static void Main()
{
Job job1 = new Job("washing windows", 5.00, 25.00);
Job job2 = new Job("walking a dog", 3.00, 11.00);
Job job3;
job3 = job1 + job2;
Console.WriteLine("The first job's description: {0} \nTotal time needed to complete the job: {1} hours \nHourly fee: {2} per hour", job1.Description, job1.Time, job1.Rate.ToString("C"));
TotalPay(job1);
Console.WriteLine("The second job's description: {0} \nTotal time needed to complete the job: {1} hours \nHourly fee: {2} per hour", job2.Description, job2.Time, job2.Rate.ToString("C"));
TotalPay(job2);
Console.WriteLine("The third job's description: {0} \nTotal time needed to complete the job: {1} hours \nHourly fee: {2} per hour", job3.Description, job3.Time, job3.Rate.ToString("C"));
TotalPay(job3);
}
public static void TotalPay(Job method)
{
double totalFee = Job.rate * Job.time;
Console.WriteLine("The total fee is: {0}", TotalFee.ToString("C"));
}
}
class Job
{
public Job(string description, double time, double rate)
{
Description = description;
Time = time;
Rate = rate;
}
public static Job operator+(Job first, Job second)
{
string newDescription = first.Description + " and " + second.Description;
double newTime = first.Time + second.Time;
double newRate = (first.Rate + second.Rate) / 2;
double newTotalFee = newRate * newTime;
return(new Job(newDescription, newTime, newRate));
}
public string Description {get; set;}
public double Time {get; set;}
public double Rate {get; set;}
}