【问题标题】:Value Returning Method C#值返回方法 C#
【发布时间】:2015-04-23 21:14:11
【问题描述】:

我需要帮助创建三个名为 GetPrice() 的重载方法。对于所有三种方法,GetPrice() 应该返回一到三个参数的价格。如果传递单个参数(价格),则默认数量为 1 且不含税。如果传递了两个参数(价格和数量),则假定没有税。如果传入三个参数,价格、数量和销售税百分比(十进制表示百分比),返回价格*数量+(价格*数量*销售税)。我是 C# 新手,不太了解,只是想知道你会做这个简单的问题。

【问题讨论】:

  • 你真的需要三个重载,还是只需要一个带默认参数的方法?
  • 你试过了吗?先试一试,如果坏了,请寻求帮助。重载很容易。
  • 能否请您尽您所能,然后发布您使用的代码,我们将尝试纠正任何问题

标签: c# methods overloading


【解决方案1】:

三种简单的方法,假设您的税是双倍百分比(即 5% 将作为 .05 传递):

public double GetPrice(double price)
{
    return price;
}

public double GetPrice(double price, double tax)
{
    return price + (price * tax);
}

public double GetPrice(double price, int quantity, double tax)
{
    return (quantity * price) + (quantity * price * tax);
}

或如@JonSkeet 所述,一种具有默认参数的方法:

public double GetPrice(double price, int quantity = 1, double tax = 0.0)
{
    return (quantity * price) + (quantity * price * tax);
}

【讨论】:

  • return (quantity * price * (1 + tax));
【解决方案2】:

还没有测试过,但是像这样的东西,应该可以让你继续前进

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

namespace ConsoleApplication3
{
    class Program
    {

        public decimal GetPrice(decimal price)
        {
            return price;
        }

        public decimal GetPrice(decimal price, int qty)
        {
            return price * qty;
        }

        public decimal GetPrice(decimal price, int qty, decimal tax)
        {
            return price * qty * tax;
        }

        static void Main(string[] args)
        {

        }
    }
}

或者更有趣的方式,因为你重用了方法:-

public decimal GetPrice(decimal price)
{
  return price
}

public decimal GetPrice(decimal price, int qty)
{
    return GetPrice(price) * quantity
}

public decimal GetPrice(decimal price, int qty, decimal tax)
{
    return GetPrice(price, qty) * tax
}

【讨论】:

  • 他确实将税收百分比表示为小数,并在他的 price * quantity + (price * quantity * sales tax) 示例中说明,这将是 0-1 之间的小数,因为此代码假定它大于 1(即 1.04 )
  • 当它只返回price 时,你为什么要GetPrice(price)?这对我来说似乎效率低下。您只需向堆栈添加更多开销即可获得您已经拥有的值...
  • VP - 是的,你是对的,EBrown - 是的,你是对的,我这样做只是为了展示如何使用重载
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2023-03-09
  • 1970-01-01
  • 2013-07-04
  • 2020-03-13
  • 2014-01-30
  • 1970-01-01
相关资源
最近更新 更多