因此,我將這張圖與我正在迭代的書一起打印出來。在一系列線性書籍中查找第n本書
public class Books : IBookFinder
{
private Books(Books next, string book)
{
Next = next;
Book = book;
}
public Books Next { get; }
public string Book { get; }
public Books Previous(string book)
{
return new Books(this, book);
}
public static Books Create(string book)
{
return new Books(null, book);
}
//This is the method I'm especially interested in implementing
public string FromLeft(Books books, int numberFromLeft)
{
Console.Writeline("This is FromLeft method");
}
}
一切都很好,但我想實現一個方法FromLeft,這樣我可以寫出來的書的名字來自它的位置在圖中,給定數量的輸入。例如,如果輸入「3」,則應輸出「暮光之城」。
class Program
{
static void Main(string[] args)
{
var curr = Books
.Create("Harry Potter")
.Previous("Lord of the Rings")
.Previous("Twilight")
.Previous("Da Vinci Code");
while (curr != null)
{
if (curr.Next != null)
{
Console.Write(curr.Book + " --- ");
}
else
{
Console.WriteLine(curr.Book);
}
curr = curr.Next;
}
Console.WriteLine("Input number to pick a book");
var bookNumber = Console.ReadLine();
int n;
if (int.TryParse(bookNumber, out n)) //Checking if the input is a #
{
}
else
{
Console.WriteLine("Input was not a number!");
}
Console.WriteLine(bookNumber);
Console.ReadLine();
}
}
任何提示,我可以如何繼續?
難道這樣的事情就足夠了? 'var book = this; while(numberFromLeft--> 0 && book.Next!= null)book = book.Next;返回書;' –