试图在c#中重写Equals方法

时间:2017-11-19 18:07:44

标签: c# casting

class Program
{
    static void Main(string[] args)
    {
        TextBook book1 = new TextBook();
        book1.ISBN = "0783161484100";
        book1.Title = "Horton Hears a Who";
        book1.Author = "Dr. Seus";
        book1.Price = 100.2423f;

        TextBook book2 = new TextBook();
        book2.ISBN = "0783161484100";
        Console.WriteLine(book1.Equals(book2.ISBN));
        Console.WriteLine("ISBN   :   " + book1.ISBN);
        Console.WriteLine("Title  :   " + book1.Title);
        Console.WriteLine("Author :   " + book1.Author);
        Console.WriteLine("Price  :   " + book1.Price.ToString("C"));
        Console.WriteLine("Price  :   " + book2.Price.ToString("C"));
    }
}

class Book
{
    public string ISBN { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public virtual float Price { get; set; }

    public override int GetHashCode()
    {
        return this.ISBN.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        bool result;
        Book otherBook = (Book)obj;
        if (this.ISBN == otherBook.ISBN)
        {
            result = true;
        }
        else
        {
            result = false;
        }

        return result;
    }
}

class TextBook : Book
{
    public string GradeLevel { get; set; }

    float price;
    public override float Price
    {
        get
        {
            return price;
        }
        set
        {
            price = value;
            if (price < 20)
            {
                price = 20;
            }
            if (price > 80)
            {
                price = 80;
            }
        }
    }
}

尝试重载Equals类方法,但我收到错误Unable to cast of type System.String to type BookDemo.Book

1 个答案:

答案 0 :(得分:0)

覆盖方法应该是:

public override bool Equals(Book otherBook)
    {
        bool result;
        if (this.ISBN == otherBook.ISBN)
        {
            result = true;
        }
        else
        {
            result = false;
        }

        return result;
    }

,用法应为:

Console.WriteLine(book1.Equals(book2));