C# 基于多态c的货币转换器#
是否可以使用多态性使货币转换器面向对象C# 基于多态c的货币转换器#,c#,polymorphism,C#,Polymorphism,是否可以使用多态性使货币转换器面向对象 public class Product { public string name; public double price; public double quantity; public Product(string name, double price, int quantity) { this.Name = name;
public class Product
{
public string name;
public double price;
public double quantity;
public Product(string name, double price, int quantity)
{
this.Name = name;
this.Price = price;
this.Quantity = quantity;
}
...
public double Price
{
get { return this.price; }
set { this.price = value; }
}
...
我有一个类产品,其中包含为程序中的每个产品设置的参数。我想得到价格并将其转换成其他货币。有没有办法用多态性做到这一点 我可以想象你可以有一组类,比如
EUR
,USD
,它们将继承自Currency
,但是每个类都应该有一个从任何可能的货币转换的方法
public class EUR : Currency
{
public override decimal ToEUR(decimal amount)
{
return amount;
}
public override decimal ToUSD(decimal amount)
{
return amount * [ratio to convert from EUR to USD];
}
// and the rest of the methods here.
}
类似于此的内容,但适用于每种受支持的货币
public class EUR : Currency
{
public override decimal ToEUR(decimal amount)
{
return amount;
}
public override decimal ToUSD(decimal amount)
{
return amount * [ratio to convert from EUR to USD];
}
// and the rest of the methods here.
}
货币应该是这样的:
public class Currency
{
public virtual decimal ToEUR(decimal amount)
{
throw new NotImplementedException();
}
public virtual decimal ToUSD(decimal amount)
{
throw new NotImplementedException();
}
// and the rest of the methods here.
}
我不确定这是否是最好的方法,但当然这取决于您的场景。我可以想象您可以有一组类,如
EUR
,USD
,它们将继承自货币
,但每个类都应该有一个从任何可能的货币转换的方法
public class EUR : Currency
{
public override decimal ToEUR(decimal amount)
{
return amount;
}
public override decimal ToUSD(decimal amount)
{
return amount * [ratio to convert from EUR to USD];
}
// and the rest of the methods here.
}
类似于此的内容,但适用于每种受支持的货币
public class EUR : Currency
{
public override decimal ToEUR(decimal amount)
{
return amount;
}
public override decimal ToUSD(decimal amount)
{
return amount * [ratio to convert from EUR to USD];
}
// and the rest of the methods here.
}
货币应该是这样的:
public class Currency
{
public virtual decimal ToEUR(decimal amount)
{
throw new NotImplementedException();
}
public virtual decimal ToUSD(decimal amount)
{
throw new NotImplementedException();
}
// and the rest of the methods here.
}
虽然我不确定这是最好的方法,但当然这取决于你的情况