C# - 操作数错误

时间:2013-11-28 00:51:05

标签: c#

我有一个提供错误的控制台应用程序:

运算符'+'不能应用于'program3_Sales.Books'和'program3_Sales.Books'类型的操作数。此行代码发生错误(红色错误行位于s1 + s2下)。我为什么会收到此错误的任何想法?感谢。

Books total = s1 + s2 + s3;

这是我的代码:

namespace Book_Sales
{
    class Program
    {
        static void Main(string[] args)
        {
            Books s1 = new Books("Cats Meow", 2000, 0.20);
            Books s2 = new Books("Bender", 4000);
            Books s3 = new Books("Carter");
            Books total = s1 + s2 + s3;
            Display(s1);
            Display(s2);
            Display(s3);
            DisplayTotal(total);
        }
        public static void Display(Books s)
        {


            Console.Write("{0} had sales totaling {1}.", s.Name, s.SalesAmount);
            Console.WriteLine(" Commission rate is {0}; commision value is {1}.",
                s.getRate(), s.Commission);
        }
        public static void DisplayTotal(Books s)
        {

            Console.Write("Total sales: {0}", s.SalesAmount.ToString("C"));
        }
    }

    class Books
    {
        readonly double RATE;
        private double salesAmount;
        private double commission;
        public string Name { get; set; }
        public double SalesAmount { get; set; }
        public double Commission { get; set; }
        public double rate { get; set; }

        public Books(string name, double salesAmount, double rate)
        {
            Name = name;
            RATE = rate;
            SalesAmount = salesAmount;


        }

        public Books (string name)
            : this(name, 0, 0)
        {
        }

        public Books(string name, double salesAmount)
            : this(name, salesAmount, 0)
        {
        }

        public double getRate()
        {
            return commission = salesAmount * rate;
        }
        //methods
    }
}

2 个答案:

答案 0 :(得分:3)

不应该像

那样
double total = s1.SalesAmount + s2.SalesAmount + s3.SalesAmount;

正如其他人提到的那样,你可以重载“+”运算符,但即使这样,总数也需要是一个双精度数,而不是类型为Book

答案 1 :(得分:0)

您可以重载+运算符:

public static double operator+(Book b1, Book b2) {
    return b1.SalesAmount + b2.SalesAmount;
}

..你可能最好手动添加它,因为它更有意义:

var result = b1.SalesAMount + b2.SalesAmount + b3.SalesAmount;

...等。