从另一个类定义一个类的变量

Roh*_*ota 1 c# oop class

以下是我需要创建的不同类的设置:

Author – AuthorId, AuthorName, DateOfBirth, State, City, Phone.
Publisher – PublisherId, PublisherName, DateOfBirth, State, City, Phone.
Category – CategoryId, CategoryName, Description.
Book – BookId, Category, Title, Author, Publisher, Description, Price, ISBN, PublicationDate.
Run Code Online (Sandbox Code Playgroud)

现在您可以看到Book中的Author和Author类中的AuthorId是相同的.如何在C#中实现这一点

Dar*_*ren 5

您的Book对象可以引用Author类内部,如下所示.

public class Author
{
    public int AuthorId { get; set; }
    public string AuthorName { get; set; }
}

public class Book
{
   private Author _author { get; set; }

   public Book(Author author)
   {
     _author = author;
   }

   public void PrintBookAuthor()
   {
     Console.WriteLine(_author.AuthorName);
   }
}
Run Code Online (Sandbox Code Playgroud)

然后设置:

Author author = new Author();
author.AuthorName = "Darren Davies";

Book programmingBook = new Book(author);
programmingBook.PrintBookAuthor();
Run Code Online (Sandbox Code Playgroud)