gpt4 book ai didi

c# - 在 C# 中使用继承在子类中应用不同折扣的问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:26 26 4
gpt4 key购买 nike

我有两个类,Customer 是基类,ValuedCustomer 是从基类继承的类。 Customer 类的折扣为 0%(类变量),ValuedCustomer(类变量)的折扣为 10%。

欠款方法使用折扣变量来确定欠款金额。我如何允许尊贵客户使用自己的折扣变量?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customer
{
public class Customer
{
private float discount = 0; //CV
public string name;
public float balance;
public string addr1;
public string addr2;
public string addr3;

public Customer(string name, float balance, string addr1, string addr2, string addr3)
{
this.name = name;
this.balance = balance;
this.addr1 = addr1;
this.addr2 = addr2;
this.addr3 = addr3;
}

public virtual float owes()
{
return Math.Abs(balance * discount - balance);
}

public override string ToString()
{
return String.Format("{0}\n{1:0.00}\n{2}\n{3}\nBalance: {4}\nDiscount: {5}%\nAmount due: {6:0.00}", name,addr1,addr2,addr3,balance,discount*100, owes());
}
}

class Program
{
static void Main(string[] args)
{
Customer c1 = new Customer("Jimmy", 100, "22 Main Street", "Naas", "Kildare");
ValuedCustomer c2 = new ValuedCustomer("Lucy", 100, "23 Main Street", "Roosky", "Roscommon");
Customer c3 = new Customer("Fred", 200, "24 Main Street", "Sneem", "Kerry");

Console.WriteLine(c1);
Console.WriteLine(c2);
Console.WriteLine(c3);
}
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customer
{
public class ValuedCustomer : Customer
{
private float discount = 0.1f;

public ValuedCustomer(string name, float balance, string addr1, string addr2, string addr3) : base(name,balance,addr1,addr2,addr3)
{
}

public override string ToString()
{
return String.Format("{0}\n{1:0.00}\n{2}\n{3}\nBalance: {4}\nDiscount: {5}%\nAmount due: {6:0.00}", name, addr1, addr2, addr3, balance, discount * 100, owes());
}
}
}

预期示例输出:

Jimmy
22 Main Street
Naas
Kildare
Balance: 100
Discount: 0%
Amount due: 100.00
Lucy
23 Main Street
Roosky
Roscommon
Balance: 100
Discount: 10%
Amount due: 90.00
Fred
24 Main Street
Sneem
Kerry
Balance: 200
Discount: 0%
Amount due: 200.00

最佳答案

在您的类层次结构中,Discount 应该是可覆盖的:

基于基类 Customer

    public class Customer
{
protected virtual float Discount => 0;
...
}

关于有值(value)的客户子类:

    public class ValuedCustomer : Customer
{
protected override float Discount => 0.1f;
...
}

现在,在 Owes() 方法中,

  return Math.Abs(balance * Discount - balance);    

将检索适合实际类实例类型的多态Discount

(注意我已经根据 .Net 规范更新了变量名)

关于c# - 在 C# 中使用继承在子类中应用不同折扣的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com