C#错误是因为同名还是错误的语法?

时间:2017-05-14 17:35:58

标签: c#

对于练习,我必须创建一个各种各样的库。项目规范表明应该有一个类BookBorrower字段:

+---------------------------+            +--------------------------+
|Book                       |            |Borrower                  |
+---------------------------+            +--------------------------+ 
|private string title       |            |private string name       |
|private string author      |            |private Book b            |
|private int ISBN           |            

和这些方法

|public Book(string,string,int)|         |public Borrower(String)  |
|public string GetAuthor()     |         |public string GetName()  |
|public string GetTitle()      |         |public Book GetBook()    |
|public int GetISBN()          |         |public void SetBook(Book)|
|// add methods, if needed     |         |                         |
+------------------------------+         +-------------------------+

所以我把它编码到我的编译器中,但是在我的Borrower类中我有错误,如:

class Borrower
{
    private string name;
    private Book b;

    public Borrower(string n)
    {
        name = n;
    }

    public string GetName()
    {
        return name;
    }

    public Book GetBook()
    {
        return b;
    }

    public void SetBook(Book) //I get an error here (Identifier expected)
    {
        Book = b; // error here says Book is type but is used as a variable
    }
}

这是我的Book课程,这里没有错误

class Book
{
    private string title, author;
    private int ISBN;

    public Book(string a, string b, int c)
    {
        title = a;
        author = b;
        ISBN = c;
    }

    public string GetAuthor()
    {
        return author;
    }

    public string GetTitle()
    {
        return title;
    }

    public int GetISBN()
    {
        return ISBN;
    }
}

我是否收到错误,因为我有一个方法 Book,它与类的名称相同,或者我可以将该类实际用作方法

1 个答案:

答案 0 :(得分:5)

此方法

public void SetBook(Book)
{
    Book = b;
}

应该改写如下:

public void SetBook(Book b)
{
    this.b = b;
}

否则作为参数传递的对象将没有名称。我使用与您的字段Book b相同的名称,因此我添加了this.b以消除歧义。