C#:如何使用非静态成员访问对象?

时间:2017-01-13 14:16:02

标签: c# object select static

我想为图书馆创建一个基本系统。我希望每本书都有一个名为“id”的非静态int变量。如何使用变量“id”从类“book”访问对象? 通过访问我的意思是我想使用“id”来更改包含我给它的“id”的对象的其他变量或访问方法。我也不想使用检查所有声明对象的“id”的switch case并返回对该对象的引用。相反,我想知道是否有办法从未知大小的列表中找到正确的对象。

<小时/> 这是我的代码:

using System;

class book
{
 public int id;
 public int price;

 public book ( int id, int price )
 {
  this.id = id;
  this.price = price;
 }

 public static book findBook ( int id )
 {
  //what do i put in here?
 }
}

class MainClass
{
 public static void Main( string[] args )
 {
  book b1 = new book( 123, 33 );
  book b2 = new book( 124, 23 );
  book chosenBook;
  int input = Convert.ToInt32( Console.ReadLine() );
  chosenBook = book.findBook( input );
  chosenBook.price = 34;
 }
}

1 个答案:

答案 0 :(得分:3)

您需要一个管理图书,数组,列表或任何其他集合的对象。例如:

            book b1 = new book(123, 33);
            book b2 = new book(124, 23);
            var books = new List<book>() { b1, b2 };
            book chosenBook;
            int input = Convert.ToInt32(Console.ReadLine());
            chosenBook = books.FirstOrDefault(b => b.id == input);
            chosenBook.price = 34;

或:

class book
{
    public int id;
    public int price;

    public book(int id, int price)
    {
        this.id = id;
        this.price = price;
    }

    public static List<book> currentBooks { get; set; } = new List<book>();

    public static book findBook(int id)
    {
        return currentBooks.FirstOrDefault(b => b.id == id);
    }
}

    class MainClass
    {
        public static void Main(string[] args)
        {
            book b1 = new book(123, 33);
            book b2 = new book(124, 23);
            book.currentBooks.Add(b1);
            book.currentBooks.Add(b2);
            book chosenBook;
            int input = Convert.ToInt32(Console.ReadLine());
            chosenBook = book.findBook(input);
            chosenBook.price = 34;
        }
    }

或:

    class book
    {
        public int id;
        public int price;

        public book(int id, int price)
        {
            this.id = id;
            this.price = price;
        }

        public static Dictionary<int, book> currentBooks { get; set; } = new Dictionary<int, book>();

        public static book findBook(int id)
        {
   book result = null;
            currentBooks .TryGetValue(id, out result);
return result;
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            book b1 = new book(123, 33);
            book b2 = new book(124, 23);
            book.currentBooks.Add(b1.id, b1);
            book.currentBooks.Add(b2.id, b2);
            book chosenBook;
            int input = Convert.ToInt32(Console.ReadLine());
            chosenBook = book.findBook(input);
            chosenBook.price = 34;
        }
    }