所以我有这本图表,我正在迭代并打印出来。
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",则应输出" Twilight"。
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();
}
}
有关我如何处理此事的任何提示?
答案 0 :(得分:3)
创建一个方法,通过书本x次迭代。
private Books FromLeft(Books book, int x){
for(var i = 1; i < x; i++){
book = book?.next; // Check for null if you're not using C#6
}
return book;
}
如果你拿错了书,你可能需要更改一些数字。
递推!!!洛尔
private Books FromLeft(Books book, int x){
if(x-- > 0) return FromLeft(book?.Next, x); // Check for null if you're not using C#6
return book;
}
要获得前一个:(我不知道让你的班级静止是多么困难)
public static class Books : IBookFinder
{
private Books(Books next, string book, Books previous)
{
Next = next;
Book = book;
Previous = previous;
}
public Books Next { get; }
public Books Previous { get; }
public string Book { get; }
public static Books Previous(this Books previous, string book)
{
return new Books(this, book, previous);
}
public static Books Create(string book)
{
return new Books(null, book, null);
}
private Books FromLeft(Books book, int x){
if(x-- > 0) return FromLeft(book?.Next, x); // Check for null if you're not using C#6
return book;
}
private Books FromRight(Books book, int x){
if(x-- > 0) return FromRight(book?.Previous, x); // Check for null if you're not using C#6
return book;
}
}